Python pandas add absolute one to positive/negative numbers in a series

Viewed 140

I've got a series of positive and negative numbers and want to increase the absolute value of every number by one, while still keeping them positive/negative. 0.2 -> 1.2 -0.3 -> -1.3 How can I do that?

3 Answers

Let us try sign from numpy

s=pd.Series([0.2,-0.3])
(s.abs()+1)*np.sign(s)
0    1.2
1   -1.3
dtype: float64

Or np.select

np.select([s>0,s<0],[s+1,s-1],default=1)
array([ 1.2, -1.3])

Also we can do np.where

np.where(s>=0,s+1,s-1)

You can do a np.where:

s += np.where(s>=0, 1, -1)

@YOBEN_S' answer sufficiently covers it within the pandas/numpy space - if you are working within lists, and outside Pandas/Numpy, the below code may suffice, as it uses the math module within python :

from math import fabs, copysign

[(fabs(ent)+1)*copysign(1,ent) for ent in l]

[1.2, -1.3]
Related