沿熊猫数据框中的列计数吗?

时间:2020-07-02 15:42:44

标签: python pandas

我有一个数据框,其中包含一列带有“名称”的列,然后这些列旁边包含值“是”,“否”或“ NaN”。我应该采取什么步骤计算每列中每个名称旁边出现“是”,“否”或“ NaN”的次数?为了给您一个更好的例子,我的意思是:

col1    col2  col3  col4
Bob       yes   yes   no
Tim       no     no   yes
Susan     yes   Nan   yes  

谢谢!

1 个答案:

答案 0 :(得分:3)

使用DataFrame.stackSeries.value_countsDataFrame.unstack的一个可能想法:

counts = (
    df.set_index('col1').astype(str).stack()
    .groupby(level=0, sort=False).value_counts().unstack(fill_value=0)
)

使用DataFrame.stackSeries.str.get_dummies的另一种可能的解决方案:

counts = df.set_index('col1').astype(str).stack().str.get_dummies().sum(level=0)

结果:

# print(counts)
       nan  no  yes
col1               
Bob      0   1    2
Tim      0   2    1
Susan    1   0    2