[英]Pandas dataframe to dictionary of lists
具有以下形式的 dataframe:
element1 | element2 | element3
cat bird plane
dog poodle cloud
pig bike sky
我想将其转换为表单列表的字典
{ 'element1' : ['cat', 'dog', 'pig'],
'element2' : ['bird', 'poodle', 'bike'],
'element3' : ['plane', 'cloud', 'sky'] }
我正在查看.to_dict
方法的文档,但似乎没有一个选项可以满足我的需要。
通常 to_dict 基于索引元素作为键值,因此转置您的 dataframe 并逐行应用列表,然后进行字典转换
df.T.apply(list,1).to_dict()
出去:
{'element1': ['cat', 'dog', 'pig'],
'element2': ['bird', 'poodle', 'bike'],
'element3': ['plane', 'cloud', 'sky']}
使用带有list
参数的DataFrame.to_dict
:
d = df.to_dict('list')
print (d)
{'element1': ['cat', 'dog', 'pig'],
'element2': ['bird', 'poodle', 'bike'],
'element3': ['plane', 'cloud', 'sky']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.