4

I have a dataframe that looks like this:

col1 col2
Yes  23123
No   23423423
Yes  34234
No   13213

I want to replace values in col2 so that if 'Yes' in col1 then return blank and if 'No' return the initial value

I want to see this:

 col1 col2
 Yes  
 No   23423423
 Yes  
 No   13213

I have tried this but 'No' is returning None:

   def map_value(x): 
      if x in ['Yes']:
         return ''
      else:
         return None

   df['col2'] = df['col1'].apply(map_value)
0

3 Answers 3

18

there are many ways to go about this, one of them is

df.loc[df.col1 == 'Yes', 'col2'] = ''

Output:

col1 col2
Yes  
No   23423423
Yes  
No   13213
2

You can use numpy for this

import pandas as pd
import numpy as np
d = {'col1': ['yes', 'no', 'yes', 'no'], 'col2': [23123,23423423,34234,13213]}
df = pd.DataFrame(data=d)
df['col2'] = np.where(df.col1 == 'yes', '', df.col2)
df
1

Created df by copying sample data from OP's post and using following command:

df=pd.read_clipboard();
df
   col1  col2
0  Yes   23123 
1  No    23423423 
2  Yes   34234 
3  No    13213 

Could you please try following.

m=df['col1']=='No'
df['col2']=df['col2'].where(m,'')
df

After running code output will be as follows:

  col1 col2
0 Yes
1 No   23423423 
2 Yes  
3 No   13213 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.