您可以使用
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]])