Carola
Carola

Reputation: 366

Create a column with the keys of a dictionary in python

I have the following dictionary and DataFrame in python:

dicti = {'328392': 1, '657728': 2, '913532': 3, '0153G23': 4, '23932Z': 5}
color num_ID other
red 1 train
green 3 car
black 5 car

I want to create a new number column with the value of the dictionary key, based on its value.

color num_ID other number
red 1 train 328392
green 3 car 913532
black 5 car 23932Z

Upvotes: 0

Views: 36

Answers (2)

T C Molenaar
T C Molenaar

Reputation: 3260

First create a dataframe from the dictionary:

df = pd.DataFrame.from_dict(dicti, orient='index').reset_index().rename(columns={'index': 'number', 0: 'num_ID'}).

Then merge the dictionary with your original dataframe to create the new column.

df_original.merge(df)

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

You can use map, but with a reverse dictionary:

df['number'] = df['num_ID'].map({v:k for k,v in dicti.items()})

Upvotes: 1

Related Questions