假设我有一个Dataframe df:
Label1 Label2 Label3
key1 col1value1 col2value1
key2 col1value2 col2value2
key3 col1value3 col2value3
dict1 = df.set_index('Label1').to_dict()
当我们有2列时,此方法有效。
预期产量:
my_dict = {key1: [col1value1,col2value1] , key2: [ col1value2,col2value2] , key3:[col1value3,col2value3] }
我可以to_dict
在Dataframe df上使用具有其他2列的键作为列表形式的值吗?
好吧,您可以使用字典理解和迭代:
print {key:row.tolist() for key,row in df.set_index('Label1').iterrows()}
{'key3': ['col1value3', 'col2value3'],
'key2': ['col1value2', 'col2value2'],
'key1': ['col1value1', 'col2value1']}
另外,我认为以下内容也可以使用:
df = df.set_index('Label1')
print df.T.to_dict(outtype='list')
{'key3': ['col1value3', 'col2value3'],
'key2': ['col1value2', 'col2value2'],
'key1': ['col1value1', 'col2value1']}
截至2017年秋季的更新; outtype
不再是关键字参数。改用orient:
In [11]: df.T.to_dict(orient='list')
Out[11]:
{'key1': ['col1value1', 'col2value1'],
'key2': ['col1value2', 'col2value2'],
'key3': ['col1value3', 'col2value3']}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句