Create a python dictionary using a pandas index

Question:

I have a dataframe where ids is the index of the dataframe and column named target.

                 target
ids                                                           
2453453  [-0.047055457]
3534533  [-0.244350435]
6445333  [0.1885366494]
8998292  [0.1285366494]
2323433  [0.5685366494]
...                 ...

I want to create a dictionary using this dataframe’s index as the key and the row number as value like

{
 2453453 : 1, 
 3534533 : 2, 
 6445333 : 3, 
 8998292 : 4, 
 2323433 : 5
}

How can I do this?

Asked By: gforce91

||

Answers:

You can create a new column and call to_dict on that column:

df.assign(new=range(1, len(df)+1))['new'].to_dict()

but it’s easier to just create a dict where the keys are the indices.

dict(zip(df.index, range(1, len(df)+1)))
# or
{k:v for v, k in enumerate(df.index, 1)}

Either way, the output is

{2453453: 1, 3534533: 2, 6445333: 3, 8998292: 4, 2323433: 5}
Answered By: cottontail

A possible solution would be to use pandas.DataFrame.reset_index with zip and dict :

d = dict(zip(df.index, df.reset_index().index+1))
#{2453453: 1, 3534533: 2, 6445333: 3, 8998292: 4, 2323433: 5}
Answered By: Timeless
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.