Add new column of dictionary values to pandas dataframe

Viewed 6206

The goal of this is to merge these two structures together: 1. Dictionary of key:value pairs (string1 : string2) -- call it c_dict. 2. Pandas DataFrames, where one of the columns contains a subset of c_dict.keys(). Let's refer to this dataframe as c_df.

I want the final structure to be a DataFrame where string 2 from the dictionary is added as an extra column to c_df.

For example:

    c_dict = { 'A' : 'aaa', 'B' : 'bbb', 'C' : 'ccc' }
    print(c_df)

      col1 col2 col3
     0 A    43   55
     1 B    59   88

And then the final product would be:

       col1 col2 col3 col4
     0  A    43   55  aaa
     1  B    59   88  bbb  
2 Answers

By using map

df['col4']=df.col1.map(c_dict)
df

  col1  col2  col3 col4
0    A    43    55  aaa
1    B    59    88  bbb

Or, using replace:

replace:

df['col4'] = df.col1.replace(c_dict)
df

  col1  col2  col3 col4
0    A    43    55  aaa
1    B    59    88  bbb

You need to type convert your col1 to string type. You can do something like

df['col1'] = df['col1'].astype(str) 

for that

Related