Skip to main content
 首页 » 编程设计

python之numpy 中 View 的 ndarray.data 行为

2025年05月04日26dyllove98

我正在尝试理解 ndarray.data 的含义numpy 中的字段(参见 N 维数组引用页的 memory layout 部分),尤其是对于数组 View 。引用文档:

ndarray.data -- Python buffer object pointing to the start of the array’s data

根据这个描述,我希望这是一个指向 ndarray 实例下的 C 数组的指针。

考虑 x = np.arange(5, dtype=np.float64) .

表格 y作为对 x 的看法使用切片:y = x[3:1:-1] .

我期待 x.data指向 0. 的位置和 y.data指向 3. 的位置.我期待 y.data 打印的内存指针因此被 3*x.itemsize 抵消来自 x.data 打印的内存指针的字节,但事实并非如此:

>>> import numpy as np 
>>> x = np.arange(5, dtype=np.float64) 
>>> y = x[ 3:1:-1] 
>>> x.data 
<memory at 0x000000F2F5150348> 
>>> y.data 
<memory at 0x000000F2F5150408> 
>>> int('0x000000F2F5150408', 16) - int('0x000000F2F5150348', 16) 
192 
>>> 3*x.itemsize 
24 

'data'输入 __array_interface与 ndarray 实例关联的字典表现得更像我期望的那样,尽管它本身可能不是指针:

>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0] 
24 

So this begs the question, what does the ndarray.data give?

提前致谢。

请您参考如下方法:

<memory at 0x000000F2F5150348>是 memoryview对象位于地址 0x000000F2F5150348 ;它提供访问权限的缓冲区位于其他地方。

内存 View 提供了 relevant official documentation 中描述的许多操作,但至少在 Python 端 API 上,它们不提供任何方法来访问它们公开的内存的原始地址。特别是 at whatevernumber number 不是您要找的。