我知道Python列表有一种方法可以返回第一个索引:
>>> l = [1, 2, 3]
>>> l.index(2)
1
Run Code Online (Sandbox Code Playgroud)
NumPy阵列有类似的东西吗?
我正在迭代一个2D数组,以使用索引值进行计算,然后将计算出的值分配给所述索引。
在NumPy文档中,提供了一个使用迭代器修改值的示例:
for x in np.nditer(a, op_flags=['readwrite']):
x[...] = 2 * x
Run Code Online (Sandbox Code Playgroud)
但是,使用以下方法跟踪索引时,这似乎不起作用:
it = np.nditer(a, flags=['multi_index'])
while not it.finished:
it[...] = . . .
it.iternext()
Run Code Online (Sandbox Code Playgroud)
但是,我可以使用这些it.multi_index值,但这似乎不必要。是否有更简单的方法可以通过不同的方法或不同的语法来实现?
it = np.nditer(a, flags=['multi_index'])
while not it.finished:
matrix[it.multi_index[0]][it.multi_index[1]] = . . .
it.iternext()
Run Code Online (Sandbox Code Playgroud)
编辑
这是一个multi_index尝试使用迭代器索引和失败来修改值的迭代示例。
matrix = np.zeros((5,5))
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
it[...] = 1
it.iternext()
Run Code Online (Sandbox Code Playgroud)
产生的错误是
TypeError Traceback (most recent call last)
<ipython-input-79-3f4cabcbfde6> in <module>()
25 it = np.nditer(matrix, flags=['multi_index'])
26 …Run Code Online (Sandbox Code Playgroud) 我有一个大的 2D numpy 数组,想在其中找到满足条件的一维数组的索引:例如,至少有一个大于给定阈值 x 的值。
我已经可以通过以下方式做到这一点,但有没有更短、更有效的方法来做到这一点?
import numpy
a = numpy.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])
indices = []
i = 0
x = 10
for item in a:
if any(j > x for j in item):
indices.append(i)
i += 1
print(indices) # gives [1]
Run Code Online (Sandbox Code Playgroud)