熊猫数据框到字典,以行索引为值?

时间:2020-11-10 05:27:06

标签: python pandas dataframe dictionary

如何将pandas df转换为使用其行索引作为值的字典?例如,假设我有df单列:

df = pd.DataFrame({
                   'ID': [3823, 4724,6233,2438],
                  })

这给了我

   ID
0  3823
1  4724
2  6233
3  2438

我想返回一个字典,该字典将是:

{3832: 0,  4724: 1, 6233: 2, 2438: 3}

谢谢!

2 个答案:

答案 0 :(得分:3)

按如下所示使用to_dict()和字典理解。

{v:k for k, v in df['ID'].to_dict().items()}

答案 1 :(得分:0)

这应该有效:

ret_dict = {df.loc[index, 'ID']:index for index in df.index}

输出:

{3823: 0, 4724: 1, 6233: 2, 2438: 3}
相关问题