Change the sign of the number in the pandas series

Viewed 408

How to change the sign in the series, if I have:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

and need to get:

1, 2, 3, -4, -5, -6, 8, 9, 10, -11, -12, -13

I need to be able to set the period (now it is equal to 3) and the index from which the function starts (now it is equal to 3).

For example, if I specify 2 as the index, I get

1, 2, -3, -4, -5, 6, 8, 9, -10, -11, -12, 13

I need to apply this function sequentially to each column, since applying to the entire DataFrame leads to a memory error.

1 Answers

Use numpy.where with integer division by (//) and modulo (%) for boolean mask:

s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

N = 3
#if default RangeIndex
m = (s.index // N) % 2 == 1
#general index
#m = (np.arange(len(s.index)) // N) % 2 == 1
s = pd.Series(np.where(m, -s, s))
print (s)
0      1
1      2
2      3
3     -4
4     -5
5     -6
6      7
7      8
8      9
9    -10
10   -11
11   -12
12    13
dtype: int64

EDIT:

N = 3
M = 1
m = np.concatenate([np.repeat(False, M), 
                   (np.arange(len(s.index) - M) // N) % 2 == 0])

s = pd.Series(np.where(m, -s, s))
print (s)
0      1
1     -2
2     -3
3     -4
4      5
5      6
6      7
7     -8
8     -9
9    -10
10    11
11    12
12    13
dtype: int64
Related