2

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?

Hannes Ovrén
  • 18,969
  • 8
  • 64
  • 72
Sonia
  • 219
  • 6
  • 19

3 Answers3

2

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
jezrael
  • 629,482
  • 62
  • 918
  • 895
0

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.

Rob
  • 3,019
  • 1
  • 17
  • 26
-1

Maybe

ds[0 if ds == 0 else math.log(ds)]
Nick
  • 1