Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace dataframe column values with dictionary keys?

Suppose I have a dictionary:

dict = {"1" : "A", "2" : "B" , "3" : "C"}

and a data frame

df = pd.DataFrame()
df["ID"] = pd.Series(["A","B","C"])
df["Desc"] = pd.Series(["Fruits","Vegs","Meat"])

The dataframe will look like this:

enter image description here

How would I replace values in column df["ID"] with dictionary keys so that I have 1,2,3 in df["ID"] instead of A,B,C?

like image 937
farheen Avatar asked Dec 18 '22 04:12

farheen


1 Answers

First create a reverse mapping:

In [363]: dict2 = {v : k for k, v in dict_.items()}

The assumption made here is that your values are unique. Now you can use pd.Series.replace:

In [367]: df.ID = df.ID.replace(dict2); df
Out[367]: 
  ID    Desc
0  1  Fruits
1  2    Vegs
2  3    Meat

Alternative solution with pd.Series.map:

In [380]: df.ID = df.ID.map(dict2); df
Out[380]: 
  ID    Desc
0  1  Fruits
1  2    Vegs
2  3    Meat

Also, I recommend you use a different name than dict, because there's already a builtin with that name.

like image 55
cs95 Avatar answered Dec 20 '22 20:12

cs95