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
?
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.
Or you can just base on pandas .
df.ID=df.ID.map((pd.DataFrame(data=d,index=['Value',]).T.reset_index().set_index('Value'))['index'])
Out[23]:
ID Desc
0 1 Fruits
1 2 Vegs
2 3 Meat
Another way to do this would be:
dict1 = pd.DataFrame(dict.items())
dict1.columns = ['ID_1',"ID"]
merge = pd.merge(df,dict1)
del merge['ID']
merge = merge.rename(columns={'ID_1': 'ID'})
Desc ID
0 Fruits 1
1 Vegs 2
2 Meat 3