python - 带有 dict.update() 的 Pandas groupby 函数
问题描述
我正在尝试对每个元素使用带有 dict.update() 函数的 Pandas groupby 函数。数据框中的示例(仅用于说明):
A B
0 icon1 {'ap1': {'item' : 1}, 'ap2': {'item' : 2}}
1 icon1 {'ap3': {'item' : 3}}
我想要做的是设置类似
df = df.groupby('A')['B'].apply(', '.join).reset_index()
但python', '.join
我需要按“A”列分组并更新“B”列中的每个元素,而不是使用 。我试过使用地图功能,但我无法实现任何有用的东西。
结果应该是:
A B
0 icon1 {'ap1': {'item' : 1}, 'ap2': {'item' : 2}, 'ap3': {'item' : 3}}
如果不从 dict 更改项目类型,这甚至可能吗?
解决方案
使用 dict 理解
df.groupby('A').B.agg(lambda s: {k:v for a in s for k, v in a.items()}).reset_index()
A B
0 icon1 {'ap1': {'item' : 1}, 'ap2': {'item' : 2}, 'ap3': {'item' : 3}}
推荐阅读
- scala - 如何在 scala 中实现一个通用函数,该函数允许添加参数并对它们求和?
- python - 如何在 Plotly Python 中更改我的散点图?
- java - 如何获取 FirebaseUser 数据
- jquery - jquery在锚标记内的斜体标记内选择一个类
- android - 队列缓冲区和文件中的错误导致我的应用程序终止
- groovy - 在 ODI 中使用 Groovy 设置数据源的订阅者
- ag-grid - 是否可以使用 ag-grid 来创建“垂直方向”的网格?(不是数据透视表)
- html - 将图像放在平行四边形内,没有曲率
- javascript - 在 javascript 中使用二维数组并尝试从中读取值会给出“未捕获的类型错误:无法读取未定义的属性 '0'”
- ms-access - 我正在尝试在访问中运行查询。当我使用 IIF 函数设置参数时,它无法正常工作。它没有读取字符串