Reputation: 482
Is there any ifelse
statement in python similar to R? I have a pandas.core.series.Series ds
of length 64843. I need to take log of each data point of this series. Some of the value in series are 0. In R I could write
ifelse(ds==0,0,log(z))
But in python I'm not seeing similar type of statement. Can you please guide me?
Upvotes: 4
Views: 2026
Reputation: 3513
I think in your case it is easier to just fill in the 0
's first and then call log
:
ds[ds == 0] = 1
ds = np.log(ds)
Be careful when you have values in your Series between 0 and 1, those will map to -Inf
and 0, so your scale will not be continuous anymore.
Upvotes: 1
Reputation: 863331
I believe you need numpy.where
generally, but for log
is possible add parameter where
to numpy.log
.
This functions return numpy 1d array, so for new Series
is necessary contructor:
s = pd.Series([0,1,5])
s1 = pd.Series(np.log(s,where=s>0), index=s.index)
Or:
s1 = pd.Series(np.where(s==0,0,np.log(s)), index=s.index)
print (s1)
0 0.000000
1 0.000000
2 1.609438
dtype: float64
Upvotes: 3