Numpy select rows based on condition

cha*_*l-f 13 python arrays numpy matrix

I'm trying to use numpy to remove rows from a two dimensional array where the first value of the row (so the element at index 0) does not match a certain condition.

I am able to do this with regular python using two loops, but I would like to do it more efficiently with numpy, e.g. with numpy.where

I have been trying various things with numpy.where and numpy.delete but I struggle with the fact that I want to select rows by using a condition that only needs to be verified by the first element, and not the second (I dont care about the value of the second element)

Here is an example where I only want to keep the rows where the first value of each row is 6.

Input:

[[0,4],
[0,5],
[3,5],
[6,8],
[9,1],
[6,1]]
Run Code Online (Sandbox Code Playgroud)

Output:

[[6,8],
[6,1]]
Run Code Online (Sandbox Code Playgroud)

Mad*_*ist 18

使用布尔掩码:

mask = z[:, 0] == 6
z[mask, :]
Run Code Online (Sandbox Code Playgroud)

这比np.where因为您可以直接使用布尔掩码而无需先将其转换为索引数组的开销要高效得多。

一个班轮:

z[z[:,0]==6, :]
Run Code Online (Sandbox Code Playgroud)

  • 我们可以让它变得更简单,因为没有“:”,它只意味着这一行:z=z[z[:,0]==6] (3认同)

rav*_*are 7

程序:

import numpy as np
np_array = np.array([[0,4],[0,5],[3,5],[6,8],[9,1],[6,1]])
rows=np.where(np_array[:,0]==6)
print(np_array[rows])
Run Code Online (Sandbox Code Playgroud)

输出:

[[6 8]
 [6 1]]
Run Code Online (Sandbox Code Playgroud)

如果你想进入 2d 列表使用

np_array[rows].tolist()
Run Code Online (Sandbox Code Playgroud)

二维列表的输出

[[6, 8], [6, 1]]
Run Code Online (Sandbox Code Playgroud)