python - 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},{},...]
解决方案
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}]
推荐阅读
- react-native - 如何使用辅助函数创建上下文
- python - 构建失败:找不到 CC 的可执行文件?基维,Buildozer
- javascript - 动态更改通过 API 调用的 URL 中的日期
- domino-appdev-pack - 在富文本文档中添加附件
- c++ - 使用 add-subdirectory 访问外部项目导致与导出集相关的 CMake 错误
- java - JPA Criteria API + PostgreSQL 按日期过滤,精确到分钟
- python - 如何从 Django 中的 F() / F() 获取浮点数
- python - 如何在 Wagtail 中添加片段描述
- python - Python:处理多个独立异常
- typescript - 在对象打字稿上添加/重命名键