Python Pandas Dataframe: Make an entire NaN string as per condition

I want to make a whole row of NaN according to a column based condition. For example, if B> 5, I want to make the whole string NaN:

Raw data frame:

'A''B'
 1  4
 3  5
 4  6
 8  7 

Make an entire string NaN if B> 5

'A''B'
 1  4
 3  5
 NaN NaN
 NaN NaN

Thank.

+4
source share
3 answers

You can also use df.loc[df.B > 5, :] = np.nan


Example

In [14]: df
Out[14]: 
   A  B
0  1  4
1  3  5
2  4  6
3  8  7

In [15]: df.loc[df.B > 5, :] = np.nan 

In [16]: df
Out[16]: 
     A    B
0  1.0  4.0
1  3.0  5.0
2  NaN  NaN
3  NaN  NaN

in human language df.loc[df.B > 5, :] = np.nancan be translated into:

assign to np.nanany column ( :) of the data frame ( df) where the condition is df.B > 5.

0
source

Use boolean indexingfor the destination value for each condition:

df[df['B'] > 5] = np.nan
print (df)
     A    B
0  1.0  4.0
1  3.0  5.0
2  NaN  NaN
3  NaN  NaN

Or DataFrame.mask, which are added by default NaNby condition:

df = df.mask(df['B'] > 5)
print (df)
     A    B
0  1.0  4.0
1  3.0  5.0
2  NaN  NaN
3  NaN  NaN

Bharath shetty:

df = df.where(~(df['B']>5))
+5

reindex

df.loc[df.B<=5,:].reindex(df.index)
Out[83]: 
     A    B
0  1.0  4.0
1  3.0  5.0
2  NaN  NaN
3  NaN  NaN
0

Source: https://habr.com/ru/post/1686638/


All Articles