我有一个 numpy 二维数组,我希望它返回列 c,其中 (r, c-1) (row r, coloumn c) 等于某个值 (int n)。
我不想迭代写类似的行
for r in len(rows):
if array[r, c-1] == 1:
store array[r,c]
,因为其中有 4000 个,而这个 2D 数组只是我必须查看的 20 个数组中的一个。
我找到了“过滤器”,但不知道如何使用它(找不到文档)。
是否有提供此类搜索的功能?
I hope I understood your question correctly. Let's say you have an array a
a = array(range(7)*3).reshape(7, 3)
print a
array([[0, 1, 2],
[3, 4, 5],
[6, 0, 1],
[2, 3, 4],
[5, 6, 0],
[1, 2, 3],
[4, 5, 6]])
and you want to extract all lines where the first entry is 2
. This can be done like this:
print a[a[:,0] == 2]
array([[2, 3, 4]])
a[:,0]
denotes the first column of the array, == 2
returns a Boolean array marking the entries that match, and then we use advanced indexing to extract the respective rows.
Of course, NumPy needs to iterate over all entries, but this will be much faster than doing it in Python.
Numpy 数组没有索引。如果您需要比数组大小中的线性更有效地执行此特定操作,那么您需要使用 numpy 以外的其他东西。