python有没有类似R的ifelse语句?我有一个长度为 64843 的 pandas.core.series.Series ds。我需要记录这个系列的每个数据点。系列中的一些值是 0。在 R 中我可以写
ifelse(ds==0,0,log(z))
但在 python 中我没有看到类似类型的语句。你能指导我吗?
请您参考如下方法:
我相信你需要numpy.where通常,但是对于 log 是可能的,将参数 where 添加到 numpy.log .
这个函数返回 numpy 1d 数组,所以对于新的 Series 是必要的构造函数:
s = pd.Series([0,1,5])
s1 = pd.Series(np.log(s,where=s>0), index=s.index)
或者:
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
