pandas DataFrame转置多列 [英] Pandas DataFrame Transpose multi columns

查看:95
本文介绍了 pandas DataFrame转置多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下数据框.

a   x   10
b   x   11
c   x   15
a   y   16
b   y   17
c   y   19
a   z   20
b   z   21
c   z   23

我想按如下所示对其进行转换:

and I want to transform it as below:

    x   y   z
a   10  16  20
b   11  17  21
c   15  19  23

目前,我正在将原始DF分成多个数据框(每个用于"a","b"和"c"),然后转置并合并.

Currently I am making the original DF into multiple Data Frames (each for "a", "b" and "c") and then transposing and merging back.

我敢肯定会有一个最佳解决方案.因此寻求帮助.

I am sure there would be an optimum solution. Hence looking for help.

推荐答案

使用 pivot :

print (df)
   A  B   C
0  a  x  10
1  b  x  11
2  c  x  15
3  a  y  16
4  b  y  17
5  c  y  19
6  a  z  20
7  b  z  21
8  c  z  23


df = df.pivot(index='A', columns='B', values='C')
print (df)
B   x   y   z
A            
a  10  16  20
b  11  17  21
c  15  19  23

set_index + unstack :

df = df.set_index(['A','B'])['C'].unstack()
print (df)
B   x   y   z
A            
a  10  16  20
b  11  17  21
c  15  19  23

如果重复使用 pivot_table meansum ...:

If duplicates use pivot_table with aggregate function like mean, sum...:

print (df)
   A  B   C
0  a  x  10 <-same a,x different C = 10
1  a  x  13 <-same a,x different C = 13
2  b  x  11
3  c  x  15
4  a  y  16
5  b  y  17
6  c  y  19
7  a  z  20
8  b  z  21
9  c  z  23


df = df.pivot_table(index='A', columns='B', values='C', aggfunc='mean')

groupby + aggregate function + set_index :

df = df.groupby(['A','B'])['C'].mean().unstack()
print (df)
B     x     y     z
A                  
a  11.5  16.0  20.0 <- (10 + 13) / 2 = 11.5
b  11.0  17.0  21.0
c  15.0  19.0  23.0

这篇关于 pandas DataFrame转置多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆