Reputation: 3774
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.
if col_3_sign_changed:
# do something
Upvotes: 0
Views: 1188
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
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
Reputation: 77837
Your specification allows a variety of values, not merely +1 and -1. I recommend that you use the following steps:
shift
the vector one positionYou can do this in one line, if you like.
Can you handle the coding from there?
Upvotes: 0