如何使用另一个Numpy数组设置多维Numpy数组的单个元素? [英] How to set single element of multi dimensional Numpy Array using another Numpy array?

查看:105
本文介绍了如何使用另一个Numpy数组设置多维Numpy数组的单个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个像numpy数组:

If we have a numpy array like:

Array = np.zeros((2, 10, 10))

我们想设置一个元素,由另一个元素给出

and we want to set one element of it, given by another

indexes = np.array([0,0,0])

我们怎么做?

Array[indexes] = 5 

将Array的FIRST维度的每个元素设置为5

is setting every element of the FIRST dimension of Array to 5

推荐答案

a 作为数据数组,将 idx 作为索引数组每行对应一个要在数据数组中设置的元素,你可以这样做 -

With a as the data array and idx as the array of indices such that each row corresponds to one element to be set in the data array, you could do -

a[tuple(idx.T)] = 5

样品运行 -

In [94]: a = np.zeros((2,2,3),dtype=int)

In [95]: idx = np.array([[0,0,0],[1,1,0],[0,1,2]])

In [96]: a[tuple(idx.T)] = 5

In [97]: a
Out[97]: 
array([[[5, 0, 0],
        [0, 0, 5]],

       [[0, 0, 0],
        [5, 0, 0]]])

In [98]: a[tuple(idx.T)] = [5,10,15] # or set different values

In [99]: a
Out[99]: 
array([[[ 5,  0,  0],
        [ 0,  0, 15]],

       [[ 0,  0,  0],
        [10,  0,  0]]])

或者,我们可以用 np来计算线性指数.ravel_multi_index 然后用 np.put 执行赋值,就像这样 -

Alternatively, we could compute the linear indices with np.ravel_multi_index and then perform the assignment with np.put, like so -

np.put(a,np.ravel_multi_index(idx.T,a.shape),5)

如果你正在处理三维数组,我们可以对三维索引进行切片并指定另一种方法,如下所示 -

If you are dealing with three dimensional arrays, we could slice the three dimensional indices and assign to have another method, like so -

a[idx[:,0],idx[:,1],idx[:,2]] = 5






如果只需要设置一个元素,只需执行 -


If it's just one element needed to be set, just do -

a[tuple(idx)] = 5

示例跑 -

In [118]: a = np.zeros((2,2,3),dtype=int)

In [119]: idx = np.array([0,0,0])

In [120]: a[tuple(idx)] = 5

In [121]: a
Out[121]: 
array([[[5, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0]]])

这篇关于如何使用另一个Numpy数组设置多维Numpy数组的单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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