转换Pandas DataFrame到字典

时间:2019-12-09 02:42:40

标签: python pandas

我有一个简单的DataFrame

      Name Format
0    cntry    int
1  dweight    str
2  pspwght    str
3  pweight    str
4   nwspol    str

我想要这样的词典:

{
    "cntry":"int",
    "dweight":"str",
    "pspwght":"str",
    "pweight":"str",
    "nwspol":"str"
}

dict["cntry"]将返回intdict["dweight"]将返回str的地方。

我该怎么办?

3 个答案:

答案 0 :(得分:2)

如何?

import pandas as pd

df = pd.DataFrame({'col_1': ['A', 'B', 'C', 'D'], 'col_2': [1, 1, 2, 3], 'col_3': ['Bla', 'Foo', 'Sup', 'Asdf']})

res_dict = dict(zip(df['col_1'], df['col_3']))

res_dict的内容:

{'A': 'Bla', 'B': 'Foo', 'C': 'Sup', 'D': 'Asdf'}

答案 1 :(得分:0)

您正在寻找DataFrame.to_dict()

来自documentation

>>> df = pd.DataFrame({'col1': [1, 2],
...                    'col2': [0.5, 0.75]},
...                   index=['row1', 'row2'])
>>> df
      col1  col2
row1     1  0.50
row2     2  0.75
>>> df.to_dict()
{'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}

如果内部字典未按照您希望的方式进行映射,则始终可以对其进行反转:

inv_dict = {v: k for k, v in original_dict['Name'].items()}

答案 2 :(得分:0)

我想你想要的是

df.set_index('Name').to_dict()['Format']

因为您要使用Name列中的值作为字典的键。

请注意,您可能想这样做:

df.set_index('Name').astype(str).to_dict()['Format']

如果您希望字典的值是字符串。