指向数组数据开头的Python缓冲区对象是什么? [英] What is a Python buffer object pointing to the start of the array’s data?

查看:56
本文介绍了指向数组数据开头的Python缓冲区对象是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A = np.arange(12)
B = A.reshape(3, 4)
A[0] = 42
print(B)
print(A)
print(np.may_share_memory(A, B))
print(A.data == B.data)

运行以上代码,令我感到惊讶的是 print(A.data == B.data)返回 False .看来A和B正在共享一些内存,并且它们的第一个元素应该共享.然后,如果 numpy.ndarray.data 是一个指向数组数据开头的对象(如文档所述),则期望在 A 上产生相同的结果,并且 B .

Running above code, I am surprised that print(A.data == B.data) returns False. It seems A and B are sharing some memory, and their first element should be shared. Then if numpy.ndarray.data is an object pointing to the start of the array’s data (as the document said), it is expected to produce the same result on A and B.

推荐答案

我更喜欢 __ array_interface __ 作为查看属性(包括数据缓冲区地址)的方式:

I prefer __array_interface__ as a way of looking at the attributes, including data buffer address:

In [766]: A = np.arange(12)
In [767]: B = A.reshape(3,4)
In [768]: A[0] = 42
In [769]: A
Out[769]: array([42,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
In [770]: B
Out[770]: 
array([[42,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [771]: A.data
Out[771]: <memory at 0xb16ef5dc>
In [772]: B.data
Out[772]: <memory at 0xb1719cdc>
In [773]: A.__array_interface__
Out[773]: 
{'data': (156295616, False),
 'descr': [('', '<i4')],
 'shape': (12,),
 'strides': None,
 'typestr': '<i4',
 'version': 3}
In [774]: B.__array_interface__
Out[774]: 
{'data': (156295616, False),
 'descr': [('', '<i4')],
 'shape': (3, 4),
 'strides': None,
 'typestr': '<i4',
 'version': 3}

A .__ array_interface __ ['data'] [0] 值确实匹配

A.data 的文档为:

Python缓冲区对象指向数组数据的开始

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

但是对于普通的Python程序员来说可能会产生误导. @ajcr 的评论更好.缓冲区对象"和数组数据缓冲区的地址之间是有区别的.

but to ordinary Python programmers that can be misleading. @ajcr's comment is better. There is a difference between 'buffer object' and the address of the arrays data buffer.

============

============

我没有使用过 data 属性.少数情况之一就是使用 ndarray 函数

I haven't used the data attribute much. One of the few cases has been to create an array using the ndarray function

我如何使用ctypes指定Numpy数组的内存地址?

In [806]: np.ndarray((4,),buffer=A.data, dtype=int, offset=12)
Out[806]: array([3, 4, 5, 6])
In [807]: np.ndarray((4,),buffer=B.data, dtype=int, offset=16)
Out[807]: array([4, 5, 6, 7])

================

================

A.data 仅打印其 repr ,并且具有以下非信息性:

A.data just prints its repr, and is just as non-informative as:

In [808]: o=object()
In [809]: o
Out[809]: <object at 0xb729fc90>

这篇关于指向数组数据开头的Python缓冲区对象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆