按两列聚合并计算 pandas 中第三列中不同值的出现次数
Aggregate by two columns and count occurrences of distinct values in third column in pandas
我在 pandas 中有一个数据集,有四列(年、月、日、寄存器)。
df_registration
data table image
我想按年和月对数据进行分组,然后统计一年中的每个月有多少'yes'和多少'no'(或者至少有多少'yes').
具有预期结果的 df 图片:
desired outcome
我试过 group_by + 计数,
g = df_registration.groupby(["year", "month"])
monthly_counts = g.aggregate({"register": pd.Series.value_counts })
但是输出没有给出预期的结果,它们只是计算两个寄存器值的数量。
尝试失败的 df 图片:
wrong
我无法让它按我想要的方式工作...
编辑!____________ 解决方案 _________________
评论中来自 alex smolyakov 的代码有效!
counts = df_registration.groupby(["year", "month"]["register"].value_counts()
the code output here
counts = df_registration.groupby(["year", "month"])["register"].value_counts()
有帮助吗?
我在 pandas 中有一个数据集,有四列(年、月、日、寄存器)。
df_registration
data table image
我想按年和月对数据进行分组,然后统计一年中的每个月有多少'yes'和多少'no'(或者至少有多少'yes').
具有预期结果的 df 图片:
desired outcome
我试过 group_by + 计数,
g = df_registration.groupby(["year", "month"])
monthly_counts = g.aggregate({"register": pd.Series.value_counts })
但是输出没有给出预期的结果,它们只是计算两个寄存器值的数量。
尝试失败的 df 图片:
wrong
我无法让它按我想要的方式工作...
编辑!____________ 解决方案 _________________
评论中来自 alex smolyakov 的代码有效!
counts = df_registration.groupby(["year", "month"]["register"].value_counts()
the code output here
counts = df_registration.groupby(["year", "month"])["register"].value_counts()
有帮助吗?