Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifelse statement in python similar to R

Tags:

python

pandas

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?

like image 896
Sonia Avatar asked Oct 20 '25 14:10

Sonia


2 Answers

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
like image 81
jezrael Avatar answered Oct 23 '25 07:10

jezrael


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.

like image 34
Rob Avatar answered Oct 23 '25 08:10

Rob