For the general case, where your search string can be in any column, you can do this:
>>> rows, cols = np.where(t == 'bar')
>>> t[rows]
array([['2', '3', '4', 'bar'],
['8', '9', '1', 'bar']],
dtype='|S11')
Answer from Jaime on Stack OverflowFor the general case, where your search string can be in any column, you can do this:
>>> rows, cols = np.where(t == 'bar')
>>> t[rows]
array([['2', '3', '4', 'bar'],
['8', '9', '1', 'bar']],
dtype='|S11')
You have to slice the array to the col you want to index:
rows = np.where(t[:,3] == 'bar')
result = t[rows]
This returns:
[[2,3,4,'bar'],
[8,9,1,'bar']]
I have a 2D array that is shaped like (10000,2). The rows in this array repeat so I call np.unique with axis=0, to get the 2D array of all the unique rows. This reduces the size down to (24,2) or something like that. Now, I have a vector and I want to find out which index in the reduced array it is equal to. So I call np.where(reduced == vector). This does not give me the row that it is equal. Rather it takes the input vector 1 number at a time and finds where in the reduced array the numbers match. This is OK since when there are two numbers that are the same consecutively, that equates to the index that I want. So I just call np.ediff1d and find where that equals 0. I was wondering if there is an easier way to do this? Thanks. Example code is given.
import numpy as np reduced = [[10,2],[15,3],[10,1],[16,5],[16,3]] vector = [15,3] results = np.where(reduced == vector) # I want the output to be 1 but I get # results[0] = [1,1,4] diffs = np.ediff1d(results[0]) # this results in [0,3] index_that_matchs = np.where(diffs == 0)[0][0] index = results[0][index_that_matchs] # this results in 1
You can just check this with the equality operator in python with numpy. Example:
>>> A = np.array([[0,2,2,1],[2,0,0,3]])
>>> A == 0
array([[ True, False, False, False],
[False, True, True, False]], dtype=bool)
np.where() does something else, see documentation. Although, it is possible to achieve this with np.where() using broadcasting. See documentation.
>>> np.where(A == 0, True, False)
array([[ True, False, False, False],
[False, True, True, False]], dtype=bool)
Try this:
import numpy as np
myarray = np.array([[0,3,4,5],[9,4,0,4],[1,2,3,4]])
ix = np.in1d(myarray.ravel(), 0).reshape(myarray.shape)
Output of ix:
array([[ True, False, False, False],
[False, False, True, False],
[False, False, False, False]], dtype=bool)
You actually don't even need where.
yy = np.array(range(12)).reshape((4,3))
yy[yy[:,1] > 2]
Output
array([[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
x = np.array([[2,3,4],[5,6,7],[1,2,3],[8,9,10]])
array([[ 2, 3, 4],
[ 5, 6, 7],
[ 1, 2, 3],
[ 8, 9, 10]])
Find the rows where the second element are >=4
x[np.where(x[:,1] >= 4)]
array([[ 5, 6, 7],
[ 8, 9, 10]])