不复制numpy数组如何改变数据属性?

编程入门 行业动态 更新时间:2024-10-28 20:21:23
本文介绍了不复制numpy数组如何改变数据属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如下我的MWE所示,在现有数组 a 返回的行为与预期的完全一样,除了 之外, .data 属性似乎有所不同。

As my MWE below shows, calling np.array(a, copy=False) on an existing array a returns something that behaves exactly as expected, except that the .data attributes seem to differ. How can this be?

>>> a # My original array array([2]) >>> b = np.array(a, copy=False) # Not-a-copy of the original array >>> b is a # The Python objects seem to be identical True >>> b.data is a.data # But their .data attributes aren't?? False >>> a.data <memory at 0x7f82ebd757c8> >>> b.data <memory at 0x7f82ebd75888> >>> b array([2]) >>> a array([2]) >>> a[:] = 3 # Changing a indeed also changes b >>> a array([3]) >>> b array([3]) >>> a.data <memory at 0x7f82ebd757c8> >>> b.data <memory at 0x7f82ebd75888>

编辑

在玩耍时,我什至发现 .data 属性在查看时会发生变化!

While playing around, I even found that the .data attribute changes while looking at it!

>>> a.data is a.data # a.data isn't equal to itself?! False >>> a.data <memory at 0x7f82ebd75948> >>> a.data <memory at 0x7f82ebd75888> # A different value than a minute ago >>> a.data <memory at 0x7f82ebd75948> >>> a.data <memory at 0x7f82ebd75888> >>> a.data <memory at 0x7f82ebd75948> >>> a.data <memory at 0x7f82ebd75888> >>> a.data <memory at 0x7f82ebd75948> >>> a.data <memory at 0x7f82ebd75888> >>> a.data <memory at 0x7f82ebd75948>

推荐答案

In [33]: a = np.array([2]) In [34]: b = np.array(a, copy=False)

一种易于理解的共享数据缓冲区检查方法是 __ array_interface __ 字典。

A nice human-readable way of checking for shared data buffer is the __array_interface__ dictionary.

In [36]: a.__array_interface__ Out[36]: {'data': (69508768, False), 'strides': None, 'descr': [('', '<i8')], 'typestr': '<i8', 'shape': (1,), 'version': 3} In [37]: b.__array_interface__ Out[37]: {'data': (69508768, False), 'strides': None, 'descr': [('', '<i8')], 'typestr': '<i8', 'shape': (1,), 'version': 3}

a.data 可以用来创建一个新数组,否则不是很有用。甚至对于大多数用途而言,这种用法也太低级了:

a.data can be used to make a new array, but otherwise isn't very useful. And even this use is too low-level for most purposes:

In [44]: c = np.ndarray(shape=(1,1), dtype=int, buffer=a.data) In [45]: c Out[45]: array([[2]]) In [46]: c.__array_interface__ Out[46]: {'data': (69508768, False), 'strides': None, 'descr': [('', '<i8')], 'typestr': '<i8', 'shape': (1, 1), 'version': 3}

更多推荐

不复制numpy数组如何改变数据属性?

本文发布于:2023-06-03 13:17:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/474748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   属性   数据   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!