如何在python中用另一个numpy数组索引一个numpy数组 [英] How to index a numpy array with another numpy array in python
问题描述
我试图用另一个数组索引一个 np.array 以便在某个索引之后我可以在任何地方都有零,但它给了我错误
I am trying to index an np.array with another array so that I can have zeros everywhere after a certain index but it gives me the error
TypeError: 只有整数标量数组可以转换为标量索引
TypeError: only integer scalar arrays can be converted to a scalar index
基本上我希望我的代码做的是,如果我有:
Basically what I would like my code to do is that if I have:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
d = np.array([2, 1, 3])
我可以做类似的事情
a[d:] = 0
给出输出
a = [[ 1 2 3]
[ 4 0 6]
[ 0 0 9]
[ 0 0 0]]
推荐答案
对于此类问题,一种广泛使用的方法是构造一个布尔掩码,将索引数组与适当的arange
进行比较:
A widely used approach for this kind of problem is to construct a boolean mask, comparing the index array with the appropriate arange
:
In [619]: mask = np.arange(4)[:,None]>=d
In [620]: mask
Out[620]:
array([[False, False, False],
[False, True, False],
[ True, True, False],
[ True, True, True]])
In [621]: a[mask]
Out[621]: array([ 5, 7, 8, 10, 11, 12])
In [622]: a[mask] = 0
In [623]: a
Out[623]:
array([[1, 2, 3],
[4, 0, 6],
[0, 0, 9],
[0, 0, 0]])
这不一定比行(或在本例中为列)迭代快.由于切片是基本的索引编制,因此即使进行多次也可能会更快.
That's not necessarily faster than a row (or in this case column) iteration. Since slicing is basic indexing, it may be faster, even if done several times.
In [624]: for i,v in enumerate(d):
...: print(a[v:,i])
...:
[0 0]
[0 0 0]
[0]
通常,如果结果涉及多个不同长度的数组或列表,则不会出现整洁"的结果.多维解决方案.要么迭代这些列表,要么退后一步跳出框框思考".
Generally if a result involves multiple arrays or lists with different lengths, there isn't a "neat" multidimensional solution. Either iterate over those lists, or step back and "think outside the box".
这篇关于如何在python中用另一个numpy数组索引一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!