python - 如何转置 Pandas 数据框以交叉制表数据框以保留所有值

标签 python pandas dataframe crosstab

假设我们有这样的数据框:

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是唯一键

dataframe

我想让 col 值变成拆分列或对它们进行交叉制表,最后看起来像这样:

enter image description here

第一种天真的方法 pd.crosstab(df.key,df.col) 在这里效果不佳:

enter image description here

此代码 pd.crosstab(df.key,df.col,values = df[['val1', 'val2', 'val3']], aggfunc = np.max) 失败以 ValueError 运行:错误的项目数量通过 3,放置意味着 1

它是如何工作的?

最佳答案

使用pivot_tableswaplevelsort_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/

相关文章:

python - Pandas 获取每组条件第一次出现的列值

javascript - 在 GET 请求中使用 django 和 AJAX 在输入更改时立即更新页面元素

r - 将两个 ggplots 转换为一个

python - 标记数据时出错。 C 错误 : out of memory pandas python, 大文件 csv

python - 从 Pandas 到字典,第一列中的值将是键,第二列中的相应值将全部在列表中

python - 根据列减去2个pyspark数据帧

python - 如何从 Pandas (同一列)中扣除值(value)?

python - 将异常保存到python中的文件

python - 为什么我的解析器无法正确理解 “numb=”?

python - 在 Pandas 中四舍五入到最接近的 1000