Jonas Palačionis
Jonas Palačionis

Reputation: 4842

Creating a dictionary out of pandas dataframe, where the value is the index

I have a pandas dataframe like so:

A
a       
b
c
d

I am trying to create a python dictionary which would look like this:

df_dict = {'a':0, 'b':1, 'c':2, 'd':3}

What I've tried:

df.reset_index(inplace=True)
df = {x : y for x in df['A'] for y in df['index']}

But the df is 75k long and its taking a while now, not even sure if this produces the result I need. Is there a neat, fast way of achieving this?

Upvotes: 2

Views: 77

Answers (3)

jezrael
jezrael

Reputation: 862671

Use dict with zip and range:

d = dict(zip(df['A'], range(len(df))))
print (d)
{'a': 0, 'b': 1, 'c': 2, 'd': 3}

Upvotes: 2

Alexandra Dudkina
Alexandra Dudkina

Reputation: 4462

You could convert series to list and use enumerate:

lst = { x: i for i, x in enumerate(df['A'].tolist()) }

Upvotes: 1

Christian Sloper
Christian Sloper

Reputation: 7510

You can do it like this:

#creating example dataframe with 75 000 rows
import uuid
df = pd.DataFrame({"col": [str(uuid.uuid4()) for _ in range(75000) ] } )  

#your bit
{ i:v for i,v in  df.reset_index().values }

It runs in seconds.

Upvotes: 1

Related Questions