本文介绍了 pandas DataFrame以值作为元组进行字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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')}

目前,我正在这样做:

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'}}

然后,我使用dict理解将键的值格式化为元组而不是字典:

Then I use a dict comprehrension to format the values of the keys as tuples instead of 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')}

我的问题是:有没有办法从熊猫DataFrame中获取我想要的格式的dict而又不会引起对dict理解的额外窃听?

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?

推荐答案

这应该有效:

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

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

这篇关于 pandas DataFrame以值作为元组进行字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 15:11