Reputation: 41
How can I convert a pandas df to a dictionary that uses its row index as the value? For example, say I have df with a single column:
df = pd.DataFrame({
'ID': [3823, 4724,6233,2438],
})
which gives me:
ID
0 3823
1 4724
2 6233
3 2438
and I want to return a dictionary that will be:
{3832: 0, 4724: 1, 6233: 2, 2438: 3}
Thanks!
Upvotes: 4
Views: 2274
Reputation: 1669
This should work:
ret_dict = {df.loc[index, 'ID']:index for index in df.index}
Output:
{3823: 0, 4724: 1, 6233: 2, 2438: 3}
Upvotes: 0
Reputation: 2614
Use to_dict() and dictionary comprehension as follows.
{v:k for k, v in df['ID'].to_dict().items()}
Upvotes: 3