Wasserwaage
Wasserwaage

Reputation: 242

Python Pandas Dataframe to Dictionary (Column Values to Keys/Values)

I have a dataframe

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

and want to convert it to a dictionary

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

None of the orient parameters for the pandas.DataFrame.to_dict function gives me this output. How do I best get the desired output?

Upvotes: 1

Views: 47

Answers (2)

steboc
steboc

Reputation: 1181

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

Upvotes: 1

jezrael
jezrael

Reputation: 862511

Create Series with index by wavelength column and then use Series.to_dict:

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

Upvotes: 1

Related Questions