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:
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
?
Or you can just base on pandas .
Another way to do this would be:
First create a reverse mapping:
The assumption made here is that your values are unique. Now you can use
pd.Series.replace
:Alternative solution with
pd.Series.map
:Also, I recommend you use a different name than
dict
, because there's already a builtin with that name.