s900n
s900n

Reputation: 3375

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.

Upvotes: 6

Views: 6122

Answers (3)

jezrael
jezrael

Reputation: 862611

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 NaNs 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))

Upvotes: 9

BENY
BENY

Reputation: 323226

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

Upvotes: 0

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

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.

Upvotes: 5

Related Questions