Create a column with the keys of a dictionary in python

Question:

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
Asked By: Carola

||

Answers:

You can use map, but with a reverse dictionary:

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

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)
Answered By: T C Molenaar
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.