![](/img/trans.png)
[英]Pivot a pandas dataframe with multiple columns
[英]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
請注意, ID
的DATETIME
重復。
我的目標是將其轉換為以下內容(如果可能,根據 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_index
和DataFrame.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.