简体   繁体   English

pandas 将跨多个列的值计数汇总到汇总中 dataframe

[英]pandas aggregate value counts across multiple columns into summary dataframe

I am looking for a way to tabulate the pandas value counts per column into a summary table.我正在寻找一种将每列的 pandas 值计数制表到汇总表中的方法。 I've found a way to acheive what I want but Pandas must have a better way to do this.我找到了实现我想要的方法,但 Pandas 必须有更好的方法来做到这一点。

the data frame has mutliple test steps with 'P' 'F' or ' ' data for each test run.数据框有多个测试步骤,每次测试运行都带有“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

the output I am looking for is:我正在寻找的 output 是:

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

I've been able to solve this by looping through each column, doing value_counts then appending it to an output array but this seems clunky.我已经能够通过遍历每一列来解决这个问题,执行 value_counts 然后将其附加到 output 数组,但这似乎很笨重。

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)

Is there a more elegant way to accomplish this?有没有更优雅的方法来实现这一点?

Use DataFrame.apply with value_counts :使用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

For change order of rows add DataFrame.reindex by list of all values in index in list in expected order:对于行的更改顺序,按预期顺序添加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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM