python - pandas如何同时计算 bool 列值和其他列的不同计数

标签 python python-3.x pandas dataframe

我有一个 Dataframe df,您可以通过运行以下代码来获得它:

import pandas as pd
from io import StringIO
    
df = """  
    month       status_review             supply_review  case_id
2023-01-01           False                    False      12             
2023-01-01           True                     True       33           
2022-12-01           False                    True       45           
2022-12-01           True                     True       45         
2022-12-01           False                    False      44
    """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

如何统计每个月有多少个status_reviews和supply_review为True以及每个月的case数量?

输出应如下所示:

    month       # of true status_review      # of true supply_review  # of case
2023-01-01           1                         1                        2
2022-12-01           1                         2                        2

我都尝试过:

df.groupby("month").sum()
df.groupby('month').agg('sum')

但是输出是:

           status_review    supply_review   case_id
month           
2022-12-01             1    2               134
2023-01-01             1    1               45

case_id 不是我想要的。我想要 case_id 的不同计数。我怎样才能达到预期的输出?

最佳答案

您可以使用.groupby().agg():

df.groupby("month").agg({
    "status_review": "sum",
    "supply_review": "sum",
    "case_id": pd.Series.nunique
})

输出:

            status_review  supply_review  case_id
month
2022-12-01              1              2        2
2023-01-01              1              1        2

关于python - pandas如何同时计算 bool 列值和其他列的不同计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75165837/

相关文章:

python - 同时学习 Ruby 和 Python 是不是一个坏主意?

Python 网页抓取暂停

python-3.x - 根据条件更新 Pandas 中的列值

python - 如何在 python session 中获取 duckdb 可见的类表对象列表?

python - Pandas Dataframe 将字符串转换为没有时间的日期

Python Tkinter Entry() 计算

Python Pandas : Parse Into new DateTime Column

python - 将 JSON 转换为 python 数据帧

python - 将 PIL 图像转换为 numpy 数组有时不起作用

python - 如何在 pandas 的应用函数中测试 nan?