Extract values from a 2D matrix based on the values of one column

时间:2018-03-25 21:00:30

标签: python arrays numpy coding-style boolean-logic

I have a 2D numpy array "X" with m rows and n columns. I am trying a extract a sub-array when the values of the column r fall in a certain range. Right now I have implemented this by looping through each and every row, which as expected is really slow. What is the simpler way to do this in python?

    for j in range(m):
        if ((X[j,r]>=lower1) & (X[j,r]<=upper1)):
            count=count+1
            if count==1:
                X_subset=X[j,:]
            else:
                X_subset=np.vstack([X_subset,X[j,:]])

For example:

X=np.array([[10,3,20],
            [1,1,25],
            [15,4,30]])

I want to get the subset of this 2D array if the values of second column are in the range 3 to 4 (r=1, lower1=3, upper1=4). The result should be:

[[ 10  3  20]
 [ 15  4  30]]

1 个答案:

答案 0 :(得分:1)

您可以使用boolean indexing

>>> def select(X, r, lower1, upper1):
...     m = X.shape[0]
...     count = 0
...     for j in range(m):
...         if ((X[j,r]>lower1) & (X[j,r]<upper1)):
...             count=count+1
...             if count==1:
...                 X_subset=X[j,:]
...             else:
...                 X_subset=np.vstack([X_subset,X[j,:]])
...     return X_subset
... 
# an example
>>> X = np.random.random((5, 5))
>>> r = 2
>>> l, u = 0.4, 0.8
# your method:
>>> select(X, r, l, u)
array([[0.35279849, 0.80630909, 0.67111171, 0.59768928, 0.71130907],
       [0.3013973 , 0.15820738, 0.69827899, 0.69536766, 0.70500236],
       [0.07456726, 0.51917318, 0.58905997, 0.93859414, 0.47375552],
       [0.27942043, 0.62996422, 0.78499397, 0.52212271, 0.51194071]])
# boolean indexing:
>>> X[(X[:, r] > l) & (X[:, r] < u)]
array([[0.35279849, 0.80630909, 0.67111171, 0.59768928, 0.71130907],
       [0.3013973 , 0.15820738, 0.69827899, 0.69536766, 0.70500236],
       [0.07456726, 0.51917318, 0.58905997, 0.93859414, 0.47375552],
       [0.27942043, 0.62996422, 0.78499397, 0.52212271, 0.51194071]])