I have read numerous posts on the internet about slicing an array, however none seems to answer my question.
I have a numpy array having three columns say A, B and Y. And all the values are either 1 or 0. I want to find out the resultant values of Y if I apply a filter on column A, i.e. if A==0, then what values of Y do I get.
As an example , here is a numpy array
A B Y
0 0 1
1 0 0
0 0 1
0 0 0
so if I choose A = 0, then Y becomes 1,1,0.
I'd really appreciate if anyone show me how to do this (using this example) when the result of one column depends on the values in the other column.
You can index by row and column simultaneously. Use Boolean indexing in the first dimension, an integer index in the second dimension:
A = np.array([[0, 0, 1],
[1, 0, 0],
[0, 0, 1],
[0, 0, 0]])
B = A[A[:, 0] == 0, 2] # array([1, 1, 0])
B = A[A[:, 0] == 0, -1] # equivalent solution, negative indices supported
Notice labels such as A
, B
, Y
do not exist with regular NumPy arrays. For selecting a specific row or column use integer indices, noting the first row or column has index 0
. A[:, 0] == 0
returns a Boolean array which is used for filtering the first dimension (rows).