Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy where() on a 2D matrix

Tags:

I have a matrix like this

t = np.array([[1,2,3,'foo'],  [2,3,4,'bar'],  [5,6,7,'hello'],  [8,9,1,'bar']]) 

I want to get the indices where the rows contain the string 'bar'

In a 1d array

rows = np.where(t == 'bar') 

should give me the indices [0,3] followed by broadcasting:-

results = t[rows] 

should give me the right rows

But I can't figure out how to get it to work with 2d arrays.

like image 462
Delta_Fore Avatar asked Jun 14 '14 12:06

Delta_Fore


People also ask

How do you access the elements of a 2D NumPy array?

Indexing a Two-dimensional Array To access elements in this array, use two indices. One for the row and the other for the column. Note that both the column and the row indices start with 0. So if I need to access the value '10,' use the index '3' for the row and index '1' for the column.

What is 2D array in NumPy?

2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.

What is NumPy Where?

The numpy. where() function returns the indices of elements in an input array where the given condition is satisfied. Syntax :numpy.where(condition[, x, y]) Parameters: condition : When True, yield x, otherwise yield y.

What is the difference between a matrix and a 2D NumPy array?

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.


2 Answers

You have to slice the array to the col you want to index:

rows = np.where(t[:,3] == 'bar') result = t1[rows] 

This returns:

 [[2,3,4,'bar'],   [8,9,1,'bar']] 
like image 143
Delta_Fore Avatar answered Oct 02 '22 23:10

Delta_Fore


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') 
like image 27
Jaime Avatar answered Oct 02 '22 23:10

Jaime