首页 > 解决方案 > GroupBy Dataframe 按一列并根据另一列获取计数

问题描述

我知道标题可能没有多大意义。鉴于以下数据,我想要单独计算 Action 值Yes和Per Month。No

这是我的数据

    Date      Action
234 2021-03-05   yes
235 2021-03-05   yes
236 2021-03-15   yes
237 2021-03-02    no
238 2021-03-05   yes
..         ...    ...
460 2020-01-10    no
461 2019-12-27    no
462 2019-12-19    no
463 2019-12-18    no
464 2019-12-17    no

当前代码

var = df.groupby(df.dt.strftime("%y-%m")).size().reset_index(name='counts')
var = var .to_dict(orient='records')

电流输出

[{date: "2021-03", count: "10"},{},...]

期望的输出

[{date: "2021-03", "yes": 2, "no": 8},{},...]

标签: pythonpandas

解决方案


pandas.DataFrame.groupby.value_counts与 一起使用unstack

new_df = df.groupby(df["Date"].dt.strftime("%y-%m"))["Action"].value_counts().unstack()
print(new_df)

输出:

Action   no  yes
Date            
19-12   4.0  NaN
20-01   1.0  NaN
21-03   1.0  4.0

to_dict然后,您可以使用以下命令将它们设为字典列表orient=="records"

new_df.reset_index().to_dict("records")

输出:

[{'Date': '19-12', 'no': 4.0, 'yes': nan},
 {'Date': '20-01', 'no': 1.0, 'yes': nan},
 {'Date': '21-03', 'no': 1.0, 'yes': 4.0}]

推荐阅读