假設我有以下玩具資料集:
count orders books
1 40 2
1 60 4
1 80 6
2 10 8
2 30 10
2 50 12
我想通過轉換資料集來創建新列,使得每列只包含orders并且books由count組
這是輸出:
orders_1 orders_2 books_1 books_2
40 10 2 8
60 30 4 10
80 50 6 12
我曾嘗試使用資料透視表,但代碼向我拋出了一個錯誤,因為它使用相同index的以及columns.
uj5u.com熱心網友回復:
用于GroupBy.cumcount計數器、樞軸DataFrame.pivot和最后展平MultiIndex in columns:
df = df.assign(g = df.groupby('count').cumcount()).pivot('g','count')
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
print (df)
orders_1 orders_2 books_1 books_2
g
0 40 10 2 8
1 60 30 4 10
2 80 50 6 12
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488330.html
標籤:熊猫
上一篇:根據值在熊貓中創建條件列
