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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 I'd like a little more information. Can you open a new question with an minimal reproducible example and link me to it? I think you might need to use a list comprehension but I can't be sure without some testing.
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 helped me, then I used pd.Series.replace. Thanks!
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.