gpt4 book ai didi

python - 切片是 Python 中的危险操作吗?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:20 25 4
gpt4 key购买 nike

我正在阅读 Ndarray documentation在 Python 中,它有以下示例。

A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements:

>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<type 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype
dtype('int32')

The array can be indexed using Python container-like syntax:

>>> # The element of x in the *second* row, *third* column, namely, 6.
>>> x[1, 2]

For example slicing can produce views of the array:

>>> y = x[:,1]
>>> y
array([2, 5])
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5])
>>> x
array([[1, 9, 3],
[4, 5, 6]])

我有 MATLAB 背景,当我们这样做时 y = x[:, 1] , y变成一个不同的 2x1 矩阵,然后改变 y 的任何元素原始矩阵没有变化 x .但是,似乎在 Python 中更改了 y 的元素。确实改变了原始数组 x .

有人可以评论是否应该避免此操作吗?因为我不想通过对数据的某些部分进行操作而意外更改我的原始数据。

最佳答案

numpy 数组中的切片是对象的 View (不同于列表中的切片将返回一个新对象),这意味着您返回的值是对原始数组的引用。转自文章Views versus copies in NumPy ,强调我的:

What is a view of a NumPy array?

As its name is saying, it is simply another way of viewing the data of the array. Technically, that means that the data of both objects is shared. You can create views by selecting a slice of the original array, or also by changing the dtype (or a combination of both). These different kinds of views are described below.

Slice views

This is probably the most common source of view creations in !NumPy. The rule of thumb for creating a slice view is that the viewed elements can be addressed with offsets, strides, and counts in the original array. For example:

>>> a = numpy.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> v1 = a[1:2]
>>> v1
array([1])
>>> a[1] = 2
>>> v1
array([2])

当您使用切片是因为您想要查看部分数据或对其应用就地完成的操作时,它是完全安全的。如果您希望就地修改数据,则需要使用 np.copy()

创建元素的新副本
>>> a = np.array([1, 5, 3, 7, 2, 3, 1, 8, 5])
>>> b = a[1:5]
>>> b
array([5, 3, 7, 2])
>>> # this will create a new array and sort it
>>> np.sort(b)
array([2, 3, 5, 7])
>>> b
array([5, 3, 7, 2])
>>> # this is done in-place, which means it will also affect `a`
>>> b.sort()
>>> a
array([1, 2, 3, 5, 7, 3, 1, 8, 5])

关于python - 切片是 Python 中的危险操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46741988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com