5

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
  • 4,994
  • 5
  • 37
  • 71

2 Answers2

4

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
  • 195,464
  • 25
  • 298
  • 322
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,289
  • 3
  • 17
  • 42
Avind
  • 86
  • 3