繁体   English   中英

我如何 pivot 和 pandas Z6A8064B5DF4794555500553C47C55057DZ (时间序列)同时具有多个列?

[英]How can I pivot a pandas dataframe (timeseries) with multiple columns at once?

我有一个pandas日期框,如下所示,以DATETIME作为索引:

                                  ID      Val1       Val2
DATETIME                                                
2019-01-18 10:35:00                A      482.84387  439.67942
2019-01-18 10:35:00                B       -5.30216   20.22247
2019-01-18 10:40:00                A     -790.63989 -810.00000
2019-01-18 10:40:00                B      257.00000  270.55490
2019-01-18 10:45:00                A       10.54820    5.64659
2019-01-18 10:45:00                B      -85.50000  -89.00000

请注意, IDDATETIME重复。

我的目标是将其转换为以下内容(如果可能,根据 ID 更改列名):

                                   A_Val1       A_Val2      B_Val1     B_Val2
DATETIME                                                
2019-01-18 10:35:00                482.84387   439.67942      -5.30216   20.22247
2019-01-18 10:40:00               -790.63989  -810.00000     257.00000  270.55490
2019-01-18 10:45:00                 10.54820     5.64659     -85.50000  -89.00000

我使用pandas.pivot但它没有用。

df_2= df_1.pivot(index=df_1.index, columns='ID', values=['Val1', 'Val2'])

错误是:

"DatetimeIndex(['2019-01-18 10:35:00', '2019-01-18 10:35:00',\n  ....],\n  dtype='datetime64[ns]', name='DATETIME', freq=None) not in index"

我不确定 go 从那里到哪里。 如果您能提供帮助,请提前致谢。

使用DataFrame.reset_index ,将DATETIME传递给index参数,最后通过f-string s 展平MultiIndex

df_2= df_1.reset_index().pivot(index='DATETIME', columns='ID', values=['Val1', 'Val2'])
df_2.columns = df_2.columns.map(lambda x: f'{x[1]}_{x[0]}')
print (df_2)
                        A_Val1     B_Val1     A_Val2     B_Val2
DATETIME                                                       
2019-01-18 10:35:00  482.84387   -5.30216  439.67942   20.22247
2019-01-18 10:40:00 -790.63989  257.00000 -810.00000  270.55490
2019-01-18 10:45:00   10.54820  -85.50000    5.64659  -89.00000

使用DataFrame.set_indexDataFrame.unstack另一种方法:

df1 = df.set_index('ID', append=True).unstack()
df1.columns = df1.columns.map(lambda c: f'{c[1]}_{c[0]}')

结果:

# print(df1)
                        A_Val1     B_Val1     A_Val2     B_Val2
DATETIME                                                       
2019-01-18 10:35:00  482.84387   -5.30216  439.67942   20.22247
2019-01-18 10:40:00 -790.63989  257.00000 -810.00000  270.55490
2019-01-18 10:45:00   10.54820  -85.50000    5.64659  -89.00000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM