Python Pandas Dataframe到字典(列值到键/值)

时间:2019-12-18 09:42:15

标签: python pandas dataframe dictionary

我有一个数据框

+---+------------+-----------+
|   | wavelength | intensity |
+---+------------+-----------+
| 1 |        400 |        12 |
| 2 |        401 |        20 |
| 3 |        402 |        25 |
+---+------------+-----------+

并希望将其转换为字典

{400:12,
 401:20,
 402:25}

pandas.DataFrame.to_dict function的{​​{3}}参数都没有给我这个输出。如何最好地获得所需的输出?

2 个答案:

答案 0 :(得分:2)

通过wavelength列创建索引系列,然后使用Series.to_dict

d = df.set_index('wavelength')['intensity'].to_dict()

答案 1 :(得分:1)

dict(zip(df['wavelength'],df['intensity']))