numpy - Extract rows from python array in python -


i have numpy array x shape (768, 8).

the last value each row can either 0 or 1, want rows value 1, , call t.

i did:

t = [x x in x if x[7]==1] 

this correct, however, list, not numpy array (in fact cannot print t.shape).

what should instead keep numpy array?

numpy's boolean indexing gets job done in vectorized manner. approach more efficient (and arguably more elegant) using list comprehensions , type conversions.

t = x[x[:, -1] == 1] 

demo:

in [232]: first_columns = np.random.randint(0, 10, size=(10, 7))  in [233]: last_column = np.random.randint(0, 2, size=(10, 1))  in [234]: x = np.hstack((first_columns, last_column))  in [235]: x out[235]:  array([[4, 3, 3, 2, 6, 2, 2, 0],        [2, 7, 9, 4, 7, 1, 8, 0],        [9, 8, 2, 1, 2, 0, 5, 1],        [4, 4, 4, 9, 6, 4, 9, 1],        [9, 8, 7, 6, 4, 4, 9, 0],        [8, 3, 3, 2, 9, 5, 5, 1],        [7, 1, 4, 5, 2, 4, 7, 0],        [8, 0, 0, 1, 5, 2, 6, 0],        [7, 9, 9, 3, 9, 3, 9, 1],        [3, 1, 8, 7, 3, 2, 9, 0]])  in [236]: mask = x[:, -1] == 1  in [237]: mask out[237]: array([false, false,  true,  true, false,  true, false, false,  true, false], dtype=bool)  in [238]: t = x[mask]  in [239]: t out[239]:  array([[9, 8, 2, 1, 2, 0, 5, 1],        [4, 4, 4, 9, 6, 4, 9, 1],        [8, 3, 3, 2, 9, 5, 5, 1],        [7, 9, 9, 3, 9, 3, 9, 1]]) 

Comments