简体   繁体   English

pandas DataFrame用值作为元组进行dict

[英]pandas DataFrame to dict with values as tuples

I have a DataFrame as follows: 我有一个DataFrame如下:

In [23]: df = pandas.DataFrame({'Initial': ['C','A','M'], 'Sex': ['M', 'F', 'F'], 'Age': [49, 39, 19]})
         df = df[['Initial', 'Sex', 'Age']]
         df

Out[23]:   
  Initial Sex  Age
0       C   M   49
1       A   F   39
2       M   F   19

My goal is to create a dict like this: 我的目标是创建一个像这样的字典:

{'C': ('49', 'M'), 'A': ('39', 'F'), 'M': ('19', 'F')}

Currently, I'm doing it like this: 目前,我这样做:

In [24]: members = df.set_index('FirstName', drop=True).to_dict('index')
         members

Out[24]: {'C': {'Age': '49', 'Sex': 'M'}, 'A': {'Age': '39', 'Sex': 'F'}, 'M': {'Age': '19', 'Sex': 'F'}}

Then I use a dict comprehrension to format the values of the keys as tuples instead of dicts: 然后我使用dict comprehrension将键的值格式化为元组而不是dicts:

In [24]: members= {x: tuple(y.values()) for x, y in members.items()}
         members

Out[24]: {'C': ('49', 'M'), 'A': ('39', 'F'), 'M': ('19', 'F')}

My question is: is there a way to get a dict in the format I want from a pandas DataFrame without incurring the additional overheard of the dict comprehension? 我的问题是:有没有办法从pandas DataFrame获得我想要的格式的dict而不会引起额外的dict理解?

This should work: 这应该工作:

df.set_index('Initial')[['Age', 'Sex']].T.apply(tuple).to_dict()

{'A': (39, 'F'), 'C': (49, 'M'), 'M': (19, 'F')}

If lists instead of tuples are okay, then you could use: 如果列表而不是元组是可以的,那么你可以使用:

In [45]: df.set_index('Initial')[['Age','Sex']].T.to_dict('list')
Out[45]: {'A': [39, 'F'], 'C': [49, 'M'], 'M': [19, 'F']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM