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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With