7

I want to replace by np.nan all the negative numbers that are in column 'b'

  • using a method on df
  • not in place.

Here's the sample frame:

pd.DataFrame({'a': [1, 2] , 'b': [-3, 4], 'c': [5, -6]})

See this question for in-place and non-method solutions.

Hatshepsut
  • 5,962
  • 8
  • 44
  • 80

2 Answers2

6

If assign counts as a method on df, you can recalculate the column b and assign it to df to replace the old column:

df = pd.DataFrame({'a': [1, 2] , 'b': [-3, 4], 'c': [5, -6]})

df.assign(b = df.b.where(df.b.ge(0)))
#   a    b  c
#0  1  NaN  5
#1  2  4.0 -6

For better chaining behavior, you can use lambda function with assign:

df.assign(b = lambda x: x.b.where(x.b.ge(0)))
Psidom
  • 209,562
  • 33
  • 339
  • 356
3

You can use the loc function.To replace the all the negative values and leverage numpy nan to replace them. sample code look like.

import numpy as np
df=pd.DataFrame({'a': [1, 2] , 'b': [-3, 4], 'c': [5, -6]})
df.loc[~(df['b'] > 0), 'b']=np.nan
Jan
  • 1,389
  • 4
  • 17
  • 43
Avind
  • 136
  • 5