[英]Pandas dataframe to dictionary of lists
Having a dataframe of the form:具有以下形式的 dataframe:
element1 | element2 | element3
cat bird plane
dog poodle cloud
pig bike sky
I want to convert it to a dictionary of lists of the form我想将其转换为表单列表的字典
{ 'element1' : ['cat', 'dog', 'pig'],
'element2' : ['bird', 'poodle', 'bike'],
'element3' : ['plane', 'cloud', 'sky'] }
I am looking at the documentation of the .to_dict
method, but none of the options seem to do what I need.我正在查看.to_dict
方法的文档,但似乎没有一个选项可以满足我的需要。
Usual to_dict bases on index elements as key values, so transpose your dataframe and apply list by row followed by dictionary conversion通常 to_dict 基于索引元素作为键值,因此转置您的 dataframe 并逐行应用列表,然后进行字典转换
df.T.apply(list,1).to_dict()
Out:出去:
{'element1': ['cat', 'dog', 'pig'],
'element2': ['bird', 'poodle', 'bike'],
'element3': ['plane', 'cloud', 'sky']}
Use DataFrame.to_dict
with list
parameter:使用带有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.