简体   繁体   English

Python DataFrame:根据条件从数据框列中获取计数?

[英]Python DataFrame : Get count from a dataframe column based on condition?

            name              status
    0       alex                pass
    1       alex                pass
    2       alex                unknown
    3       marcus              pass
    4       marcus              fail
    5       anthony             fail
    6       paul                pass
    7       paul                unknown
    8       paul                fail
    9       paul                pass

if one the name column record has status = pass .如果name列记录具有status = pass I'm trying get count of status = pass我正在尝试获取status = pass计数status = pass

            name            count      
    0       alex              2   
    1       marcus            1     
    2       anthony           0       
    3       paul              2

You can aggregate sum of boolean mask, because True s are processing like 1 :您可以聚合布尔掩码的sum ,因为True正在处理像1

df = df['status'].eq('pass').groupby(df['name']).sum().reset_index(name='count')
print (df)
      name  count
0     alex      2
1  anthony      0
2   marcus      1
3     paul      2

We can use pd.crosstab and index on the column of interest:我们可以在感兴趣的列上使用pd.crosstab和 index :

pd.crosstab(df.name, df.status)['pass'].reset_index()

      name  pass
0     alex     2
1  anthony     0
2   marcus     1
3     paul     2

       

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

相关问题 Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe Groupby dataframe 并根据列条件计数 - Groupby dataframe and count based on column condition python count dataframe列值满足条件 - python count dataframe column values meeting condition 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python Python Dataframe:根据条件为列分配值? - Python Dataframe: Assign values to a column based on condition? Python根据条件追加到dataframe列 - Python append to dataframe column based on condition 根据另一列的条件计算来自 dataframe 列的给定列表中元素的频率 - Count frequency of elements from a given list taken from a dataframe column based on a condition from another column Python DataFrame:基于另一列的出现次数 - Python DataFrame: count of occurances based on another column 根据条件从 dataframe 获取一列到另一列 - getting a column from dataframe to anoter based on condition Python:在 Pandas 中,根据条件从数据帧中的几列中提取数据,并添加到列上的不同数据帧匹配中 - Python: In Pandas extract data from several columns in a dataframe based on a condition and add to different dataframe matching on a column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM