簡體   English   中英

pandas pivot 多列表

[英]pandas pivot table on multiple columns

輸入表

pcd 收入 教育 1 至 20 歲 甘油三酯
a1001 INCOME_1 教育_1 1個 1個
a1003 INCOME_2 教育_2 0 2個
a1001 INCOME_3 教育_2 5個 2個
a1002 INCOME_2 教育_2 1個 5個
a1003 INCOME_1 教育_2 3個 4個

必填 OUTPUT

pcd INCOME_1 INCOME_2 INCOME_3 教育_1 教育_2 1 至 20 歲 甘油三酯
a1001 1個 0 1個 1個 1個 6個 1.5
a1002 0 1個 0 0 1個 1個 5個
a1003 1個 1個 0 0 2個 3個 3個

pcd 是指數,income1、income2、income3、education1、education2、age 聚合為總和,而 TG 聚合為平均值。

pd.pivot_table(df, index=['pcd', 'age1to_20'],
           aggfunc={'INCOME':sum,'Education'=sum,'age1to_20'=sum,'TG':avg},fill_value=0)

試過上面的代碼但沒有成功

你可以先melt ,然后pivot_table重塑,最后groupby.agg組合'pcd':

agg_funcs = {'TG': 'mean', 'pcd': 'first'}

out = (df
   .melt(['pcd', 'age1to_20', 'TG'])
   .assign(v=1)
   .pivot_table(index=['pcd', 'age1to_20', 'TG'], columns='value',
                values='v', fill_value=0)
   .reset_index().rename_axis(columns=None)
   .pipe(lambda d: d.groupby('pcd', as_index=False)
                    .agg({c: agg_funcs.get(c, 'sum') for c in d.columns}))
)

Output:

     pcd  age1to_20   TG  Education_1  Education_2  INCOME_1  INCOME_2  INCOME_3
0  a1001          6  1.5            1            1         1         0         1
1  a1002          1  5.0            0            1         0         1         0
2  a1003          3  3.0            0            2         1         1         0

作為替代方案,您可以使用 crosstab 和 groupby:

x=pd.crosstab(df['pcd'],columns=df['INCOME'])
print(x)
'''
INCOME  INCOME_1  INCOME_2  INCOME_3
pcd                                 
a1001          1         0         1
a1002          0         1         0
a1003          1         1         0
'''

y=pd.crosstab([df['pcd']],columns=[df['Education']])
z=df.groupby('pcd').agg({'age1to_20':'sum','TG':'mean'})
final=x.join([y,z])
print(final)
'''
       INCOME_1  INCOME_2  INCOME_3  Education_1  Education_2  age1to_20   TG
pcd                                                                          
a1001         1         0         1            1            1          6  1.5
a1002         0         1         0            0            1          1  5.0
a1003         1         1         0            0            2          3  3.0
'''

您還需要指定值的來源以及哪些列將指定您的新列名。

另外,我不太清楚你的價值觀來自哪里。

但它看起來像這樣,例如,

pd.pivot_table(df, index=['pcd', 'age1to_20'], 
           values=['age1to_20']
           columns=['income', 'education']
           aggfunc={'INCOME':sum,'TG':avg},fill_value=0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM