【问题标题】:Pivot columns while retaining original column headers在保留原始列标题的同时旋转列
【发布时间】:2018-09-09 18:12:06
【问题描述】:

我想按 Column 和 groupby 索引计算 yes 和 no 值的数量。

我有这个数据框 :

col0  col1 col2
A     yes  no
A     no   no
B     yes  yes
B     yes  no

我想要这个:

   col1     col2
   yes  no  yes  no
A  1    1   0    2
B  2    0   1    1

我试过df.pivot_table(index='my_index', aggfunc='count') 但我只得到了

   col1     col2

A  2        2
B  2        2

【问题讨论】:

  • @Wen,我尝试了一些枢轴解决方案,但它们似乎不起作用。有什么想法吗?
  • @Wen 嗯,看看那个输出,好像不一样?
  • @cᴏʟᴅsᴘᴇᴇᴅ 是的pd.concat([pd.crosstab(df.col0,[df.col1.astype('category')]),pd.crosstab(df.col0,[df.col2.astype('category')])],axis=1,keys=['col1','col2'])
  • @Wen 啊,这绝对比简单的支点问题更复杂...我将重新打开这个问题,所以请把它作为答案发布;)
  • @cᴏʟᴅsᴘᴇᴇᴅ 是的,我想是的,我们应该重新打开它

标签: python pandas pivot-table


【解决方案1】:

选项 1
pd.get_dummies + groupby + sum

v = pd.get_dummies(df.set_index('col0'))

v.columns = pd.MultiIndex.from_tuples(
    list(map(tuple, v.columns.str.split('_')))
)
v.sum(level=0)

     col1     col2    
       no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1

选项 2
stack + get_dummies + unstack

(df.set_index('col0')
   .stack()
   .str.get_dummies()
   .sum(level=[0,1])
   .unstack(-1)
   .swaplevel(0, 1, axis=1)
   .sort_index(level=0, axis=1)
)

     col1     col2    
       no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1

选项 3
crosstab + concat @Wen

i = pd.crosstab(df.col0, df.col1.astype('category'))
j = pd.crosstab(df.col0, df.col2.astype('category'))

pd.concat([i, j], axis=1, keys=['col1','col2'])

     col1     col2    
col1   no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1

【讨论】:

  • 伙计,只需将其添加到您的答案中,没有您的提醒,我差点杀死一个好问题..pd.concat([pd.crosstab(df.col0,[df.col1.astype('category')]),pd.crosstab(df.col0,[df.col2.astype('category')])],axis=1,keys=['col1','col2'])
  • @Wen 我没有看到你的答案,请再发一次,这样我就可以投票了;)
  • 如果你不介意人,你能补充你的答案吗?不好意思发帖回答...:-(
  • @Wen 这是一个很好的答案,可惜你没有自己发布。我已经添加了,干杯
  • @cᴏʟᴅsᴘᴇᴇᴅ 谢谢!它完美地工作!我应该更改问题的标题吗?,Wich 是这个问题的好标题吗?
猜你喜欢
  • 2010-09-18
  • 2022-11-23
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
相关资源
最近更新 更多