简体   繁体   中英

Python pandas.DataFrame: Make whole row NaN according to condition

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

Unprocessed data frame looks like this:

   A  B
0  1  4
1  3  5
2  4  6
3  8  7

Make whole row NaN, if B > 5 :

     A    B
0  1.0  4.0
1  3.0  5.0
2  NaN  NaN
3  NaN  NaN

Thank you.

Use boolean indexing for assign value per 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 add by default NaN s by 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

Thank you Bharath shetty :

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

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.nan can be translated to:

assign np.nan to any column ( : ) of the dataframe ( df ) where the condition df.B > 5 is valid.

Or using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM