Reputation: 6662
I want to replace by np.nan
all the negative numbers that are in column 'b'
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.
Upvotes: 7
Views: 11731
Reputation: 171
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
Upvotes: 3
Reputation: 214977
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)))
Upvotes: 6