【问题标题】:pandas aggregate value counts across multiple columns into summary dataframepandas 将跨多列的值计数汇总到摘要数据框中
【发布时间】:2020-04-14 04:57:31
【问题描述】:

我正在寻找一种将每列的熊猫值计数制表到汇总表中的方法。我找到了实现我想要的方法,但 Pandas 必须有更好的方法来做到这一点。

数据框有多个测试步骤,每次测试运行都包含 'P' 'F' 或 ' ' 数据。

step1 = list('PPFP PFP ')
step2 = list('PFFP  FPF')
step3 = list(' PPPFFPFP')
step4 = list(' PPFPF PP')

df = pd.DataFrame({'step1': step1,'step2':step2, 'step3':step3,'step4':step4})

  step1 step2 step3 step4
0     P     P            
1     P     F     P     P
2     F     F     P     P
3     P     P     P     F
4                 F     P
5     P           F     F
6     F     F     P      
7     P     P     F     P
8           F     P     P

我正在寻找的输出是:

   step1  step2  step3  step4
P      5      3      5      5
F      2      4      3      2
       2      2      1      2

我已经能够通过遍历每一列、执行 value_counts 然后将其附加到输出数组来解决这个问题,但这似乎很笨重。

df2 = pd.DataFrame(index=['P', 'F', ' '])

for i in range(len(df.columns)):
    df2[df.columns.tolist()[i]] = df.iloc[:, i].value_counts(dropna=False)

有没有更优雅的方法来实现这一点?

【问题讨论】:

    标签: python pandas aggregate unique


    【解决方案1】:

    DataFrame.applyvalue_counts 一起使用:

    df2 = df.apply(pd.value_counts)
    print (df2)
       step1  step2  step3  step4
           2      2      1      2
    F      2      4      3      2
    P      5      3      5      5
    

    对于行的更改顺序,按预期顺序在列表中的索引中的所有值的列表中添加DataFrame.reindex

    df2 = df.apply(pd.value_counts).reindex([' ','P','F'])
    print (df2)
       step1  step2  step3  step4
           2      2      1      2
    P      5      3      5      5
    F      2      4      3      2
    

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 1970-01-01
      • 2020-02-24
      • 2020-08-22
      • 2019-08-18
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多