4

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
farheen
  • 111
  • 2
  • 3
  • 13

3 Answers3

9

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    how would you do it if your values in your dictionary are a list? Say you found the value in the original dataframe to replace as a value in a list under a key. How would you replace it with that key? I tried your approach, but the first line gives me this error: `TypeError: unhashable type: 'list'` – florence-y Aug 17 '18 at 15:41
  • @florence-y I'd like a little more information. Can you open a new question with an [mcve] and link me to it? I think you might need to use a list comprehension but I can't be sure without some testing. – cs95 Aug 17 '18 at 17:23
  • I managed to figure this out on my own -- I played around a bit and got the keys and values to switch with `dict2 = {keys: old_keys for old_keys, old_values in dict.items() for keys in old_values}`, then used `df.columnheader.replace(dict2)` to get what I needed. This question [here](https://stackoverflow.com/questions/31674403/swap-dictionary-keys-and-values-when-values-are-lists) helped me, then I used `pd.Series.replace`. Thanks! – florence-y Aug 17 '18 at 18:09
2

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
BENY
  • 317,841
  • 20
  • 164
  • 234
0

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
Gayatri
  • 2,197
  • 4
  • 23
  • 35