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.

2 Answers 2

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)))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.