gpt4 book ai didi

Python:当一个数组转置时,numpy 数组是否链接?

转载 作者:太空狗 更新时间:2023-10-30 02:58:10 25 4
gpt4 key购买 nike

目前我正在开发一个 python 脚本,它从文本文件中提取测量数据。我正在使用 iPython Notebook 和 Python 2.7

现在我在使用 numpy 数组时遇到了一些奇怪的行为。我对此没有任何解释。

myArray = numpy.zeros((4,3))
myArrayTransposed = myArray.transpose()

for i in range(0,4):
for j in range(0,3):
myArray[i][j] = i+j

print myArray
print myArrayTransposed

导致:

[[ 0.  1.  2.]
[ 1. 2. 3.]
[ 2. 3. 4.]
[ 3. 4. 5.]]
[[ 0. 1. 2. 3.]
[ 1. 2. 3. 4.]
[ 2. 3. 4. 5.]]

因此,无需处理转置数组,该数组中的值就会更新。

这怎么可能?

最佳答案

来自 http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html :

Different ndarrays can share the same data, so that changes made in one ndarray may be visible in another. That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects implementing the buffer or array interfaces.

当你执行 transpose() 时,这会返回原始 ndarray 的“ View ”。它指向相同的内存缓冲区,但具有不同的索引方案:

A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an N-dimensional array in a 1-dimensional block. Numpy is flexible, and ndarray objects can accommodate any strided indexing scheme.

要创建一个独立的 ndarray,可以使用 numpy.array() 运算符:

myArrayTransposed = myArray.transpose().copy()

关于Python:当一个数组转置时,numpy 数组是否链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34945360/

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