gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:24:16 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com