python - 数据结构;将元组列表转换为字典

标签 python python-3.x pandas dictionary

我有一个元组列表

data = [
    ('di', 'c1', 'avg11'),
    ('di', 'c2', 'stdev12'),
    ('eng', 'c1', 'stdev21'),
    ('eng', 'c2', 'stdev22')
]

如何将 'di''eng' 项目放入字典中,如下所示:

data1 = {'c1':'avg11','c2':'stdev12'}

data2 = {'c1':'stdev21','c2':'stdev22'}

使用 pandas 或 numpy 或常规 python?

最佳答案

使用 Pandas 你可以做到

In [660]: data1, data2 = pd.DataFrame(data).set_index([0, 1]).unstack()[2].to_dict('r')

In [661]: data1
Out[661]: {'c1': 'avg11', 'c2': 'stdev12'}

In [662]: data2
Out[662]: {'c1': 'stdev21', 'c2': 'stdev22'}

In [663]: pd.DataFrame(data).set_index([0, 1]).unstack()[2].to_dict('r')
Out[663]: [{'c1': 'avg11', 'c2': 'stdev12'}, {'c1': 'stdev21', 'c2': 'stdev22'}]

关于python - 数据结构;将元组列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46253668/

相关文章:

python - 在django中使用多个数据库

python - pandas:groupby 两列 nunique

python - 获取 Pandas 中 groupby 操作的大小

python - 从随机森林导出特征重要性到 csv

python - 使用 Rpy2 将 Pandas DataFrame 转换为 R dataframe

Python matplotlib如何将颜色映射到饼图中的 'x-values'

python - pyinstaller 启动服务时出错 : The service did not respond to the start or control request in a timely fashion

python - 使用其中一个子词典的值对所有子词典进行排序

python - PyCharm 将多个 df 导出到单个 csv 文件

python - PyQT4:为什么当 setVisible(false) 时 QDialog 从 exec_() 返回