2
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.

4
  • 1
    Can you rephrase the question, specifically can you give more details about the "dataframe": is it a text file, array or some sort of data-structure? Maybe provide some existing code, MWE. Commented Nov 15, 2018 at 5:28
  • @EmilVatai There is a csv file with above dataframe.A and B are column of object type.I've to replace few values in rows of column A i.e a01 and a02 with values in dictionary d but the condition is only if B is equal to CN. Commented Nov 15, 2018 at 6:00
  • pandas.DataFrame? That part of your question is very vague... You want to change the csv or the datastructure? Could you provide a MVE? Commented Nov 15, 2018 at 6:22
  • X=pd.read_csv('somefile.csv). A and B are columns in X.I've to replace few rows in A which have values a01 and a02 but only if the values in column B is BN.I've created a dictionary d whose value are to be used for replacing rows in A.For example: a01 should be replaced by ana only if rows in B have value equal to CN .Is it clear now? Commented Nov 15, 2018 at 7:18

2 Answers 2

1

In a single line in would look 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

Also you can use np.where:

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

Here is the whole code with 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
Sign up to request clarification or add additional context in comments.

2 Comments

0n applying it,I get 'nan' for replaced values in A.
@VroJ I've added code for your example and it works as intended.
0

Use map to use the dictionary for mapping the values and loc to assign the values to the particular slice:

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

    A   B
0   abc AN
1   abd BN
2   ana CN
3   abc BN
4   aza CN

1 Comment

0n applying it,I get 'nan' for replaced values in A.There is a warning "A value is trying to be set on a copy of a slice from a DataFrame".

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.