我有一个时间序列数据集,如下所示:
df <- tibble(location = c('f1','f1','f1','f1'),
year = c('1999','1999','1999','1999'),
day = c('01-01','01-02','01-01','01-02'),
variable = c('var1','var1','var2','var2'),
value = c(1.0, 3.0, "option1","option2"))在R中,我可以转换这种数据结构,使用位置+年份作为1轴,天作为另一个轴,变量作为第三个变量,并使用reshape2::acast。
> reshape2::acast(df, location + year ~ day ~ variable)
, , var1
01-01 01-02
f1_1999 "1" "3"
, , var2
01-01 01-02
f1_1999 "option1" "option2"如何使用Pandas dataframe实现同样的效果?我的第一次尝试是使用pivot或pivot_table,但我想我误解了它们的工作方式:pandas.pivot_table(df, index = ['location','year'], columns = 'day', values = 'variable')生成错误DataError: No numeric types to aggregate。给了一只熊猫数据:
import pandas as pd
df = pd.DataFrame({
'location': ['f1','f1','f1','f1'],
'year': ['1999','1999','1999','1999'],
'day': ['01-01','01-02','01-01','01-02'],
'variable': ['var1','var1','var2','var2'],
'value': [1.0, 3.0, 'option1','option2']
})有没有办法在R中实现相同的数据结构(比如numpy数组)?
发布于 2018-10-24 20:11:38
像这样的东西会把你的数据重塑成一个MultiIndexed DataFrame,这是处理大熊猫中的> 2D数据的一种方法。注意aggfunc的变化-通常它默认为一个数字聚合,即lambda只是不改变地通过数据。
res = df.pivot_table(index=['location', 'year'],
columns=['variable', 'day'],
values='value',
aggfunc=lambda x: x)
res
Out[7]:
variable var1 var2
day 01-01 01-02 01-01 01-02
location year
f1 1999 1 3 option1 option2从那里,请参阅MultiIndexing文档获得更多信息。例如,选择出day == '01-02'
idx = pd.IndexSlice
res.loc[:, idx[:, '01-02']]
Out[12]:
variable var1 var2
day 01-02 01-02
location year
f1 1999 3 option2https://stackoverflow.com/questions/52976678
复制相似问题