Skip to main content
 首页 » 编程设计

python之在 Pandas 中按组划分列

2024年10月24日7myhome

如果我有这样的 DataFrame:

 type   value   group 
    a      10     one 
    b      45     one 
    a     224     two 
    b     119     two 
    a      33   three 
    b      44   three 

我如何做到这一点:

 type     one     two   three 
    a      10     224      33 
    b      45     119      44 

我以为它会是 pivot_table,但这只是给了我一个重新分组的列表。

请您参考如下方法:

我想你需要pivot与 rename_axis (pandas 0.18.0 中的新功能)和 reset_index :

print df.pivot(index='type', columns='group', values='value') 
        .rename_axis(None, axis=1) 
        .reset_index() 
 
  type  one  three  two 
0    a   10     33  224 
1    b   45     44  119 

如果列的顺序很重要:

df = df.pivot(index='type', columns='group', values='value').rename_axis(None, axis=1) 
 
print df[['one','two','three']].reset_index() 
  type  one  two  three 
0    a   10  224     33 
1    b   45  119     44 

编辑:

在你的真实数据中你会得到错误:

print df.pivot(index='type', columns='group', values='value') 
        .rename_axis(None, axis=1) 
        .reset_index() 

ValueError: Index contains duplicate entries, cannot reshape

print df 
  type  value  group 
0    a     10    one 
1    a     20    one 
2    b     45    one 
3    a    224    two 
4    b    119    two 
5    a     33  three 
6    b     44  three 

问题在第二行 - 你得到索引值 a 和列 one 两个值 - 10 和 20。函数pivot_table在这种情况下聚合数据。默认的聚合函数是np.mean,但是你可以通过参数aggfunc来改变它:

print df.pivot_table(index='type', columns='group', values='value', aggfunc=np.mean) 
        .rename_axis(None, axis=1) 
        .reset_index() 
 
  type  one  three  two 
0    a   15     33  224 
1    b   45     44  119 
 
print df.pivot_table(index='type', columns='group', values='value', aggfunc='first') 
        .rename_axis(None, axis=1) 
        .reset_index() 
 
  type  one  three  two 
0    a   10     33  224 
1    b   45     44  119 
 
print df.pivot_table(index='type', columns='group', values='value', aggfunc=sum) 
        .rename_axis(None, axis=1) 
        .reset_index() 
 
  type  one  three  two 
0    a   30     33  224 
1    b   45     44  119