RustyShackleford
RustyShackleford

Reputation: 3677

How to clear value from cell if value in another column is present?

I have df that looks like this:

col1    col2 
NaN     text
text    text
NaN     text
NaN     text

I want to clear the value in col2 if NaN if present in col1.

New df should look like this:

col1    col2 
NaN     
text    text
NaN     
NaN     

Upvotes: 2

Views: 41

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133710

1st Step: Create df by copying OP's sample.(copy OP's sample first and then run following command).

df=pd.read_clipboard();

2nd Step: Could you please try following here.

df.loc[df['col1'].isnull(), 'col2'] = ''
df

Output will be as follows.

   col1  col2
0  NaN
1  text  text 
2  NaN
3  NaN  

Upvotes: 0

BENY
BENY

Reputation: 323366

Using dropna + reindex

df.dropna('col1').reindex(df.index) # fixing by cold :-)

   col1  col2
0   NaN   NaN
1  text  text
2   NaN   NaN
3   NaN   NaN

Upvotes: 1

cs95
cs95

Reputation: 402922

You're looking for a masking operation:

df['col2'] = df['col2'].mask(df.col1.isna(), '')
# df['col2'] = np.where(df.col1.isna(), '', df['col2'])

df
   col1  col2
0   NaN      
1  text  text
2   NaN      
3   NaN      

If you want NaNs in the second column instead of blanks, omit the second parameter to mask.

Upvotes: 3

Related Questions