Python pandas 给系列中的 positive/negative 个数字加绝对值
Python pandas add absolute one to positive/negative numbers in a series
我有一系列正数和负数,想将每个数字的绝对值增加一,同时仍保持它们 positive/negative。
0.2 -> 1.2
-0.3 -> -1.3
我怎样才能做到这一点?
让我们试试 sign
从 numpy
s=pd.Series([0.2,-0.3])
(s.abs()+1)*np.sign(s)
0 1.2
1 -1.3
dtype: float64
或np.select
np.select([s>0,s<0],[s+1,s-1],default=1)
array([ 1.2, -1.3])
我们也可以np.where
np.where(s>=0,s+1,s-1)
你可以做一个 np.where
:
s += np.where(s>=0, 1, -1)
@YOBEN_S' 的回答充分涵盖了 pandas/numpy
space - 如果你在列表中工作,并且在 Pandas/Numpy 之外,下面的代码可能就足够了,因为它在 python 中使用 math 模块:
from math import fabs, copysign
[(fabs(ent)+1)*copysign(1,ent) for ent in l]
[1.2, -1.3]
我有一系列正数和负数,想将每个数字的绝对值增加一,同时仍保持它们 positive/negative。 0.2 -> 1.2 -0.3 -> -1.3 我怎样才能做到这一点?
让我们试试 sign
从 numpy
s=pd.Series([0.2,-0.3])
(s.abs()+1)*np.sign(s)
0 1.2
1 -1.3
dtype: float64
或np.select
np.select([s>0,s<0],[s+1,s-1],default=1)
array([ 1.2, -1.3])
我们也可以np.where
np.where(s>=0,s+1,s-1)
你可以做一个 np.where
:
s += np.where(s>=0, 1, -1)
@YOBEN_S' 的回答充分涵盖了 pandas/numpy
space - 如果你在列表中工作,并且在 Pandas/Numpy 之外,下面的代码可能就足够了,因为它在 python 中使用 math 模块:
from math import fabs, copysign
[(fabs(ent)+1)*copysign(1,ent) for ent in l]
[1.2, -1.3]