作者:臻艾龙522_292 | 来源:互联网 | 2023-10-12 14:37
I've a little issue while working on same big data. But for now, let's assume I've got an NumPy array filled with zeros
我在处理大数据的时候有个小问题。现在,假设我有一个满是0的NumPy数组
>>> x = np.zeros((3,3))
>>> x
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
Now I want to change some of these zeros with specific values. I've given the index of the cells I want to change.
现在我想用特定的值来改变其中的一些0。我已经给出了要改变的单元格的索引。
>>> y = np.array([[0,0],[1,1],[2,2]])
>>> y
array([[0, 0],
[1, 1],
[2, 2]])
And I've got an array with the desired (for now random) numbers, as follow
我得到了一个具有期望(现在是随机的)数字的数组,如下所示
>>> z = np.array(np.random.rand(3))
>>> z
array([ 0.04988558, 0.87512891, 0.4288157 ])
So now I thought I can do the following:
所以现在我想我可以做以下的事:
>>> x[y] = z
But than it's filling the whole array like this
而不是像这样填满整个数组
>>> x
array([[ 0.04988558, 0.87512891, 0.4288157 ],
[ 0.04988558, 0.87512891, 0.4288157 ],
[ 0.04988558, 0.87512891, 0.4288157 ]])
But I was hoping to get
但我希望得到。
>>> x
array([[ 0.04988558, 0, 0 ],
[ 0, 0.87512891, 0 ],
[ 0, 0, 0.4288157 ]])
EDIT
编辑
Now I've used a diagonal index, but what in the case my index is not just diagonal. I was hoping following works:
现在我用了一个对角指数,但在这个情况下,我的索引不仅仅是对角线。我希望接下来的工作:
>>> y = np.array([[0,1],[1,2],[2,0]])
>>> x[y] = z
>>> x
>>> x
array([[ 0, 0.04988558, 0 ],
[ 0, 0, 0.87512891 ],
0.4288157, 0, 0 ]])
But it's filling whole array just like above
但是它像上面一样填充了整个数组
1 个解决方案
5
Array indexing works a bit differently on multidimensional arrays
数组索引在多维数组上的工作方式略有不同
If you have a vector, you can access the first three elements by using
如果你有一个向量,你可以使用
x[np.array([0,1,2])]
but when you're using this on a matrix, it will return the first few rows. Upon first sight, using
但是当你在矩阵上使用它时,它会返回前几行。在第一眼看到,使用
x[np.array([0,0],[1,1],[2,2]])]
sounds reasonable. However, NumPy array indexing works differently: It still treats all those indices in a 1D fashion, but returns the values from the vector in the same shape as your index vector.
听起来很合理。但是,NumPy数组的工作方式不同:它仍然以一维的方式处理所有这些索引,但是返回与索引向量相同形状的向量的值。
To properly access 2D matrices you have to split both components into two separate arrays:
要正确地访问2D矩阵,你必须将两个组件分割成两个独立的数组:
x[np.array([0,1,2]), np.array([0,1,2])]
This will fetch all elements on the main diagonal of your matrix. Assignments using this method is possible, too:
这将获取矩阵主对角线上的所有元素。使用这种方法分配任务也是可能的:
x[np.array([0,1,2]), np.array([0,1,2])] = 1
So to access the elements you've mentioned in your edit, you have to do the following:
因此,要访问您在编辑中提到的元素,您必须执行以下操作:
x[np.array([0,1,2]), np.array([1,2,0])]