ajayramesh
ajayramesh

Reputation: 3774

Find sign change in set of positive and negative numbers using numpy?

I have set of numbers, in which column index 3 has negative and positive numbers, so there is change of pattern from positive to negative. How to check this using Numpy array, I am thinking to count the sum of column and if its less then number of rows then there is a sign change happend. Is there any function in Numpy to do it more efficiently, may be something like XOR ?

import numpy as np
t = [[363.57, 363.57, 1, 1, 1, 1, 1, 1],
 [385.41, 385.41, 1, -1, 1, 1, 1, 1],
 [406.12, 406.12, 1, -1, 1, 1, 1, 1],
 [424.2, 424.2, 1, -1, 1, 1, 1, 1],
 [444.91, 444.91, 1, -1, 1, 1, 1, 1],
 [468.26, 468.26, 1, -1, 1, 1, -1, 1]]

x = np.array(t)
x[:, 3]

I dont like below solution, because its too bulky if I have more than 100 K Rows.

if sum(x[:, 3]) <= x.shape[0]:
   print("sign change happend")

I can change the datastructure, that is how I am storing it in variable t. trying to do it in more efficient and fast way using numpy.

expected output

if col_3_sign_changed: 
   # do something 

Upvotes: 0

Views: 1188

Answers (3)

anon01
anon01

Reputation: 11171

Your question could be clearer, but if you are looking for whether there are positive and negative values vs just positive, something this simple will suffice:

value_signs = set(np.sign(x[:,3]).flatten())

if len(value_signs) == 2:
    print("positive and negative signs present")
else:
    print("just one sign present")

Upvotes: 1

Ehsan
Ehsan

Reputation: 12397

Here are some options:

np.any(np.diff(x[:,3]))

or (suggested in question):

np.sign(x[:,3]).sum()<x.shape[0]

or (as suggested by @Prune):

np.any(np.roll(x[:,3],1)!=x[:,3])

Upvotes: 2

Prune
Prune

Reputation: 77837

Your specification allows a variety of values, not merely +1 and -1. I recommend that you use the following steps:

  • create a vector of Booleans, indicating + and - values
  • shift the vector one position
  • compare the shifted vector with the original

You can do this in one line, if you like.

Can you handle the coding from there?

Upvotes: 0

Related Questions