I have a matrix and a boolean vector:
>>>from numpy import *
>>>a = arange(20).reshape(4,5)
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>>b = asarray( [1, 1, 0, 1] ).reshape(-1,1)
array([[1],
[1],
[0],
[1]])
Now I want to select all the corresponding rows in this matrix where the corresponding index in the vector is equal to zero.
>>>a[b==0]
array([10])
How can I make it so this returns this particular row?
[10, 11, 12, 13, 14]
In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to the given conditions. Whenever we need to perform analysis, slicing plays an important role.
We can also index NumPy arrays using a NumPy array of boolean values on one axis to specify the indices that we want to access. This will create a NumPy array of size 3x4 (3 rows and 4 columns) with values from 0 to 11 (value 12 not included).
Slice a Range of Values from Two-dimensional Numpy Arrays For example, you can use the index [0:1, 0:2] to select the elements in first row, first two columns. You can flip these index values to select elements in the first two rows, first column.
In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix. Return: The number of rows and columns.
The shape of b
is somewhat strange, but if you can craft it as a nicer index it's a simple selection:
idx = b.reshape(a.shape[0])
print a[idx==0,:]
>>> [[10 11 12 13 14]]
You can read this as, "select all the rows where the index is 0, and for each row selected take all the columns". Your expected answer should really be a list-of-lists since you are asking for all of the rows that match a criteria.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With