pandas - Pandas 数据框以列中的唯一值作为键和嵌套列表作为值进行 dict
问题描述
我试图将数据框转换为字典,并使用来自列(col 3)的唯一值作为键。
由此:
Col1 Col2 Col3
0 a b x
1 c d x
2 e f y
3 g h y
对此:
{x:[[a,b][c,d]],y:[[e,f],[g,h]]}
使用下面的代码,我得到了元组,这对我来说真的没有用。
new_dict = df.groupby('col3').apply(lambda x: list(zip(x['col1'],x['col2']))).to_dict()
输出:
{x:[(a,b),(c,d)],y:[(e,f),(g,h)]}
解决方案
用于map
列出或列出理解:
new_dict = (df.groupby('col3')
.apply(lambda x: list(map(list, zip(x['col1'],x['col2']))))
.to_dict())
print (new_dict)
{'x': [['a', 'b'], ['c', 'd']], 'y': [['e', 'f'], ['g', 'h']]}
new_dict = (df.groupby('col3')
.apply(lambda x: [list(y) for y in zip(x['col1'],x['col2'])])
.to_dict())
另一种解决方案是将每个组转换为二维数组并转换为list
:
new_dict = df.groupby('col3')['col1','col2'].apply(lambda x: x.values.tolist()).to_dict()
推荐阅读
- java - Maven依赖导入错误的子依赖版本
- arduino - 检测气球的图像处理
- amazon-web-services - AMI 创建对网络带宽有影响吗
- sql-server - 在没有报表服务器的情况下捕获运行的报表
- json - 如何根据打字稿中对象内的键值对从JSON数组中获取对象而不循环
- c++ - Tensorflow C++ r1.13 构建错误:“TopK”不是“tensorflow::ops”的成员
- flutter - “_Type”不是“Widget”类型的子类型
- c# - 调用 TextBox.AppendText() 后显示自动完成列表
- apache - .htaccess:将 x.com/sub/ 重定向到 y.com/sub/
- python - a = 1000, b = 1000。为什么从命令行运行时`a is b`返回true,但在解释器中却没有?