假设我们有这样的数据框:
df = pd.DataFrame({'key' : ['one', 'two', 'three', 'four'] * 3,
'col' : ['A', 'B', 'C'] * 4,
'val1' : np.random.randn(12),
'val2' : np.random.randn(12),
'val3' : np.random.randn(12)})
key + col
是唯一键
我想让 col
值变成拆分列或对它们进行交叉制表,最后看起来像这样:
第一种天真的方法 pd.crosstab(df.key,df.col)
在这里效果不佳:
此代码 pd.crosstab(df.key,df.col,values = df[['val1', 'val2', 'val3']], aggfunc = np.max)
失败以 ValueError 运行:错误的项目数量通过 3,放置意味着 1
它是如何工作的?
最佳答案
使用pivot_table
与 swaplevel
和 sort_index
使用聚合函数 np.max
:
df = (df.pivot_table(index='key', columns='col', aggfunc=np.max)
.swaplevel(0,1,axis=1)
.sort_index(axis=1))
备选方案由 GroupBy.max
聚合:
df = (df.groupby(['key', 'col'])
.max()
.unstack()
.swaplevel(0,1,axis=1)
.sort_index(axis=1))
print (df)
col A B C \
val1 val2 val3 val1 val2 val3 val1
key
four -0.225967 0.362041 0.040915 -1.227718 -0.879248 -1.279912 -1.577218
one -0.187167 1.530731 -1.112116 -0.871077 -2.099876 -0.069297 -0.351971
three -0.165375 -0.378049 -0.390724 0.484519 -0.408990 -1.496042 0.590083
two 1.923084 -0.688284 1.702659 -0.159921 0.635245 0.623821 -1.503893
col
val2 val3
key
four -1.135872 0.645371
one 2.347472 0.129252
three 0.402825 0.883710
two -0.132847 0.179476
关于python - 如何转置 Pandas 数据框以交叉制表数据框以保留所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764465/