python - 使用列的唯一值作为索引对数据框进行分组
问题描述
按值对数据帧索引的不同值进行分组或堆叠的最有效方法是什么?
这个df:
color alert
blue A
blue B
red A
green C
到:
color alert
blue [A, B]
red A
green C
解决方案
您需要 agroupby
和聚合成 a list
:
df.groupby('color').alert.agg(list).reset_index()
color alert
0 blue [A, B]
1 green [C]
2 red [A]
推荐阅读
- c++ - 忽略 SIGSEGV 并继续执行
- json-api - 为 API JSON 响应格式化数据
- docker - 如何从称为地点的地方排除依赖的罐子 pom.xml
- reactjs - React lazy 不会导致将包拆分成块
- regex - Django url随参数传递而变化
- kubernetes - Re-use PersistentVolume after re-installing a helm deployment
- c++ - 如何创建自定义组件?访问私有字段时出错
- jquery - Jquery Ajax - 使用动态分页获取 API 调用
- excel - 在 Excel 工作表中搜索并根据带有层次结构的 where 子句返回一个值?
- apache-spark - Spark - 使用多个“何时”优化查询