如何在没有循环的情况下在特定位置修改2D numpy数组? [英] how to modify a 2D numpy array at specific locations without a loop?

查看:115
本文介绍了如何在没有循环的情况下在特定位置修改2D numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D numpy数组,并且有一个行和列的数组,应将其设置为特定值.让我们考虑以下示例

I have a 2D numpy array and I have a arrays of rows and columns which should be set to a particular value. Lets consider the following example

 a = array([[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]])

我想修改第[0,2]行和第[1,2]列的条目.这应该导致以下数组

I want to modify entries at rows [0,2] and columns [1,2]. This should result in the following array

 a = array([[1, 2, 0],
           [4, 5, 0],
           [7, 8, 9]])

我照做了,结果导致修改了每一行中的每个列顺序

I did following and it resulted in modifying each sequence of column in every row

rows = [0,1]
cols = [2,2]
b=a[numpy.ix_(rows,columns)]

这导致以下数组修改了指定数组的每一列

It resulted in the following array modifying every column of the specified array

array([[1, 0, 0],
       [4, 5, 6],
       [7, 0, 0]])

有人可以让我知道怎么做吗?

Some one could please let me know how to do it?

非常感谢

要注意的是,行和列碰巧是偶然的.实际的观点是,这些可以是任意的,也可以是任意顺序.如果它是rows = [a,b,c]和cols = [nxz],那么我想精确地修改位置(a,n),(b,x),(c,z)的三个元素.

推荐答案

除了别人所说的以外,您还可以使用花哨索引来修改这些元素,如下所示:

Adding to what others have said, you can modify these elements using fancy indexing as follows:

In [39]: rows = [0,1]

In [40]: cols = [2,2]

In [41]: a = np.arange(1,10).reshape((3,3))

In [42]: a[rows,cols] = 0

In [43]: a
Out[43]: 
array([[1, 2, 0],
       [4, 5, 0],
       [7, 8, 9]])

您可能想阅读有关索引多维数组的文档: http://docs.scipy.org /doc/numpy/user/basics.indexing.html#indexing-multi-Dimension-arrays

You might want to read the documentation on indexing multidimensional arrays: http://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays

关键点是:

如果索引数组具有匹配的形状,并且存在索引数组 对于要索引的数组的每个维,结果数组具有 与索引数组具有相同的形状,并且值对应于 为索引数组中每个位置设置的索引.

if the index arrays have a matching shape, and there is an index array for each dimension of the array being indexed, the resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays.

重要的是,这还允许您执行以下操作:

Importantly this also allows you to do things like:

In [60]: a[rows,cols] = np.array([33,77])

In [61]: a
Out[61]: 
array([[ 1,  2, 33],
       [ 4,  5, 77],
       [ 7,  8,  9]])

您可以在其中使用相同大小的另一个数组,列表或元组独立设置每个元素.

where you can set each element independently using another array, list or tuple of the same size.

这篇关于如何在没有循环的情况下在特定位置修改2D numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆