Finding Non-zero Values/indexes In Numpy
I have a quite big numpy array with the shape of (12388, 4). The first two values are coordiantes and the second two key values. Some of the are zero. I want to filter through the
Solution 1:
Here's a working demo. Create test data:
import numpy as np
X = np.random.rand(10,4)
X = np.vstack([X, np.zeros([2,4])])
>>> X
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
[0.67277149, 0.01654403, 0.17710642, 0.54201684],
# ...
[0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. ]])
Find vectors the last two numbers are none zero:
idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]
# alternatively, use np.anyidx = np.where(np.any(X[:,2:], axis=1))[0]
Retrieve filtered vectors:
X_none_zeros = X[idx]
>>>X_none_zeros
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
# ...
[0.78279739, 0.84191242, 0.31685306, 0.54906034]])
>>>X_none_zeros.shape
(10, 4)
>>>X.shape
(12, 4)
Explain: the actual codes are just two lines:
# retrieve last 2 numbers for each vector in X# and sum each vector horizontally, so you have # [s1, s2, s3, ...]# use the condition to filter indexesidx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]
# retrieve matched vectors accordinglyX_none_zeros = X[idx]
Post a Comment for "Finding Non-zero Values/indexes In Numpy"