Sonia
Sonia

Reputation: 482

ifelse statement in python similar to R

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

Answers (3)

Rob
Rob

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

jezrael
jezrael

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

Nick
Nick

Reputation: 1

Maybe

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

Upvotes: -1

Related Questions