I'm looking for a short readable way to select some rows of an 2D numpy.ndarray, where the first number of each row is in some list.
Example:
>>> index
[4, 8]
>>> data
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
So in this case i only need
array([[ 4, 5, 6, 7],
[8, 9, 10, 11]])
because the first numbers of these rows are 4 and 8 which are listed in index
.
Basically im looking for something like:
data[data[:,0] == i if i in index]
which of course is not working.
You can use np.isin
to check, then index as usual:
idx = [4, 8]
data = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> data[np.isin(data[:,0], idx)]
array([[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
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