python - pandas DataFrame 将值作为元组进行字典

标签 python pandas dictionary 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

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

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

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

最佳答案

这应该有效:

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

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

关于python - pandas DataFrame 将值作为元组进行字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133332/

相关文章:

python - 在数据框中查找必须包含列表中至少 2 个元素的行

python - 我应该使用哪个语句来替换创建虚拟变量的自定义函数以提高 python 中的速度?

python - Pandas - df.fillna(df.mean()) 不适用于多索引 DataFrame

python - 向 .csv 写入多于一列

java - 从 map 中检索对象

python - 从带有边标签的邻接矩阵绘制加权图

python 模块,如 csv-DictReader,具有完整的 utf8 支持

python - Cython纯python模式

python - 使用 python 重新采样数据帧时出错

python - 如何按相同字段合并字典列表并在此过程中对另一个字段求​​和?