[英]How to extend pandas Dataframe by values in multiindex column?
我有一張由 groupby() 獲取的 Multiindex 表:
new_data=data.groupby(['id','category']).sum('amount')
new_data
Output 看起來像這樣(只是一個與我的表格相同的隨機表):
# amount
#id category
1 2 12
3 1
2 1 45
3 56
Unique Id 在每個類別中都有一定數量。
但我需要得到一個表,其中顯示了同一列中每個類別的每個“id”的數量。
像這樣的東西:
#id amount_category_1 amount_category_2 amount_category_3
1 0 12 1
2 45 0 56
假設您重置了 dataframe 的索引並采用以下形式:
id category amount
0 1 1 45
1 1 3 34
2 2 2 36
3 2 3 24
你可以 pivot 你的 dataframe 並重命名你的列:
df = df.pivot_table(index='id',columns='category',values='amount').rename_axis(None, axis=1).reset_index()
df = df.rename(columns={c: 'category_'+ str(c) for c in df.columns if c not in ['id']})
得到這樣的東西:
id category_1 category_2 category_3
0 1 45.0 NaN 34.0
1 2 NaN 36.0 24.0
使用df.fillna(0)
改變NaN
得到
id category_1 category_2 category_3
0 1 45.0 0.0 34.0
1 2 0.0 36.0 24.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.