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

2024-10-01 07:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在编写一个python脚本,它从文本文件中提取测量数据。我正在使用iPython笔记本和python2.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

导致:

^{pr2}$

因此,在不处理转置数组的情况下,将更新该数组中的值。在

这怎么可能?在


Tags: 数据innumpy脚本foripythonzeros笔记本
1条回答
网友
1楼 · 发布于 2024-10-01 07:37:25

来自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()时,将返回原始nArray的“视图”。它指向相同的内存缓冲区,但有不同的索引方案:

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,可以使用数字阵列()操作员:

myArrayTransposed = myArray.transpose().copy()

相关问题 更多 >