如何在DataFrame上应用Series.value_counts()?

时间:2019-02-05 22:33:33

标签: python pandas dataframe

在DataFrame中,我想计算每一列的值并将其用作索引。

我想打开它:

Q1                   Q2                  Q3
Strongly agree       Agree               Undecided
Undecided            Agree               More or less disagree
Strongly agree       Agree               Undecided
Strongly agree       Strongly Disagree   Disagree
More or less agree   Undecided           Strongly disagree

为此:

                        Q1  Q2  Q3
Strongly agree          3   0   0
Agree                   0   3   0
More or less agree      1   0   0
Undecided               1   1   2
More or less disagree   0   0   1
Disagree                0   0   1
Strongly disagree       0   1   1

大熊猫怎么可能?

2 个答案:

答案 0 :(得分:3)

如果您坚持使用value_counts,则可以先使用stackgroupby,然后在value_counts之前致电unstacking

df.stack().groupby(level=[1]).value_counts().unstack(0, fill_value=0)

                       Q1  Q2  Q3
Agree                   0   3   0
Disagree                0   0   1
More or less agree      1   0   0
More or less disagree   0   0   1
Strongly Disagree       0   1   0
Strongly agree          3   0   0
Strongly disagree       0   0   1
Undecided               1   1   2

另一种选择是使用meltpivot_table

(df.melt()
   .pivot_table(columns='variable', index='value', aggfunc='size', fill_value=0))

variable               Q1  Q2  Q3
value                            
Agree                   0   3   0
Disagree                0   0   1
More or less agree      1   0   0
More or less disagree   0   0   1
Strongly Disagree       0   1   0
Strongly agree          3   0   0
Strongly disagree       0   0   1
Undecided               1   1   2

使用crosstab的解决方案:

v = df.melt()
pd.crosstab(v['value'], v['variable'])

variable               Q1  Q2  Q3
value                            
Agree                   0   3   0
Disagree                0   0   1
More or less agree      1   0   0
More or less disagree   0   0   1
Strongly Disagree       0   1   0
Strongly agree          3   0   0
Strongly disagree       0   0   1
Undecided               1   1   2

答案 1 :(得分:2)

您可以将const函数应用于整个数据框,并用0填充let值。

let