【问题标题】:pandas DataFrame to dict with values as tuplespandas DataFrame 将值作为元组进行 dict
【发布时间】:2016-11-03 03:40:01
【问题描述】:

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

我的目标是创建一个这样的字典:

{'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 comprehrension 将键的值格式化为元组而不是字典:

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 理解?

【问题讨论】:

  • 你想把年龄变成字符串吗?
  • @unutbu 没关系。

标签: python pandas dictionary dataframe


【解决方案1】:

这应该可行:

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

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

【讨论】:

  • 您可以将axis=1 传递给apply(),而不是转置(T)。
  • @chrisaycock 同意谢谢。为了简洁起见,我选择了T。
【解决方案2】:

如果列表而不是元组是可以的,那么你可以使用:

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

【讨论】:

  • 我需要元组,但感谢您的回答!我投了赞成票。
猜你喜欢
  • 2018-02-15
  • 1970-01-01
  • 2017-01-28
  • 2021-07-16
  • 2021-11-06
  • 2020-12-31
  • 2013-12-28
  • 2018-08-11
相关资源
最近更新 更多