user6400946
user6400946

Reputation: 116

How to differentiate between negative and positive sign changes in a series or numpy array

I would like to differentiate between negative and positive sign changes in a series or an array.

    series  sign_change (desired output)
0       -2                             0
1       -4                             0
2       -2                             0
3        1                             1
4        2                             0
5        8                             0
6       -1                            -1
7       -1                             0
8        0                             1
9        1                             1
10      -1                            -1
11       2                             1
12       2                             0

In other words, I would like to have a 1 for a change from negative to positive, and a -1 for a change from positive to negative.

A similar question was posed here, but not answered correctly, in my opinion: Detect sign changes in Pandas Dataframe

Any ideas how to solve this in pandas or numpy?

Here is the df to play around with:

import pandas as pd
pd.DataFrame({'series': {0: -2,
  1: -4,
  2: -2,
  3: 1,
  4: 2,
  5: 8,
  6: -1,
  7: -1,
  8: 0,
  9: 1,
  10: -1,
  11: 2,
  12: 2},
 'sign_change (desired output)': {0: 0,
  1: 0,
  2: 0,
  3: 1,
  4: 0,
  5: 0,
  6: -1,
  7: 0,
  8: 1,
  9: 1,
  10: -1,
  11: 1,
  12: 0}})

Upvotes: 1

Views: 392

Answers (2)

igrinis
igrinis

Reputation: 13626

Same principle, more pandas style:

result = np.sign( np.sign(df['series']).diff().fillna(0) )

Upvotes: 2

Marat
Marat

Reputation: 15738

np.diff(np.sign(arr)) will do almost everything, but will be one element short (first element is nothing to compare to). It only remains to insert leading zero and convert -2 and 2 to -1 and 1:

result = np.clip(np.insert(np.diff(np.sign(arr)), 0, 0), -1, 1)

Upvotes: 3

Related Questions