Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

A    B

abc  AN 

abd  BN

a01  CN

abc  BN

a02  CN

I have a dataframe similar to above. For every B=CN,I want to replace corresponding row in A i.e a01,a02 with value from dictionary. The dictionary is as follow:

d={'a01':'ana','a02':'aza'}

Whenever I'm trying to replace the values, it's giving incorrect result either the values are misplaced. I tried where clause as well but still missing something.

1 Answer

0 votes
by (41.4k points)

Code will be like this:

df.loc[df['B'].eq('CN'), 'A'] = df['A'].map(d)

df

     A   B

0  abc  AN

1  abd  BN

2  ana  CN

3  abc  BN

4  aza  CN

Code using np.where:

import pandas as pd

import numpy as np

df = pd.DataFrame({'A': ['abc', 'abd', 'a01', 'abc', 'a02'],

                   'B': ['AN', 'BN', 'CN', 'BN', 'CN']})

d = {'a01': 'ana', 'a02': 'aza'}

df['A'] = np.where(df['B'].eq('CN'), df['A'].map(d), df['A'])

df

     A   B

0  abc  AN

1  abd  BN

2  ana  CN

3  abc  BN

4  aza  CN

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...