Home > database >  Create a column with the keys of a dictionary in python
Create a column with the keys of a dictionary in python

Time:09-13

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

CodePudding user response:

You can use map, but with a reverse dictionary:

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

CodePudding user response:

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)
  • Related