[英]Change Numpy array values in-place
Say when we have a randomly generated 2D 3x2 Numpy array a = np.array(3,2)
and I want to change the value of the element on the first row & column (ie a[0,0]) to 10. If I do假设我们有一个随机生成的 2D 3x2 Numpy 数组a = np.array(3,2)
并且我想将第一行和第一列(即 a[0,0])上元素的值更改为 10。如果我愿意
a[0][0] = 10
then it works and a[0,0] is changed to 10. But if I do然后它可以工作,并且 a[0,0] 更改为 10。但是如果我这样做
a[np.arange(1)][0] = 10
then nothing is changed.然后什么都没有改变。 Why is this?为什么是这样?
I want to change some columns values of a selected list of rows (that is indicated by a Numpy array) to some other values (like a[row_indices][:,0] = 10
) but it doesn't work as I'm passing in an array (or list) that indicates rows.我想将所选行列表的某些列值(由 Numpy 数组指示)更改为其他一些值(如a[row_indices][:,0] = 10
),但它不像我那样工作传入指示行的数组(或列表)。
a[x][y]
is wrong . a[x][y]
是错误的。 It happens to work in the first case, a[0][0] = 10
because a[0]
returns a view , hence doing resul[y] = whatever
modifies the original array.它恰好在第一种情况下起作用, a[0][0] = 10
因为a[0]
返回一个view ,因此执行resul[y] = whatever
修改原始数组。 However, in the second case, a[np.arange(1)][0] = 10
, a[np.arange(1)]
returns a copy (because you are using array indexing).但是,在第二种情况下, a[np.arange(1)][0] = 10
, a[np.arange(1)]
返回一个副本(因为您使用的是数组索引)。
You should be using a[0, 0] = 10
or a[np.arange(1), 0] = 10
您应该使用a[0, 0] = 10
或a[np.arange(1), 0] = 10
Advanced indexing always returns a copy as a view cannot be guaranteed. 高级索引始终返回副本,因为无法保证视图。
Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).高级索引始终返回数据的副本(与返回视图的基本切片相反)。
If you replace np.arange(1)
with something that returns a view (or equivalent slicing) then you get back to basic indexing, and hence when you chain two views, the change is reflected into the original array.如果您将np.arange(1)
替换为返回视图(或等效切片)的内容,那么您将返回基本索引,因此当您链接两个视图时,更改会反映到原始数组中。
For example:例如:
import numpy as np
import numpy as np
arr = np.arange(2 * 3).reshape((2, 3))
arr[0][0] = 10
print(arr)
# [[10 1 2]
# [ 3 4 5]]
arr = np.arange(2 * 3).reshape((2, 3))
arr[:1][0] = 10
print(arr)
# [[10 10 10]
# [ 3 4 5]]
arr = np.arange(2 * 3).reshape((2, 3))
arr[0][:1] = 10
print(arr)
# [[10 1 2]
# [ 3 4 5]]
etc.等等
If you have some row indices you want to use, to modify the array you can just use them, but you cannot chain the indexing, eg:如果您有一些要使用的行索引,要修改数组,您可以使用它们,但不能链接索引,例如:
arr = np.arange(5 * 3).reshape((5, 3))
row_indices = (0, 2)
arr[row_indices, 0] = 10
print(arr)
# [[10 1 2]
# [ 3 4 5]
# [10 7 8]
# [ 9 10 11]
# [12 13 14]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.