numpy recarray 副本保留 dtype 引用?
我正在尝试复制重新数组并更改新数组中的字段/记录的名称。但是,这会修改原始数组的名称(但是,这些值并不是取消链接的)。示例:
import numpy as np
import copy
定义原始数组
arr = np.array(np.random.random((3,2)),
dtype=[('a','float'),('b','float')])
第一个副本
arr2 = arr.copy()
arr2.dtype.names = ('c','d')
arr.dtype.names
--> ('c','d')
第二个副本
arr3 = copy.deepcopy(arr2)
arr2.dtype.names = ('e','f')
arr.dtype.names
--> ('e','f')
为什么会发生这种情况以及如何防止这种情况发生?我怀疑 dtype
是一个单独的列表/对象,其引用是在 copy()
上复制的,但即使我分配了 dtype
的深层副本> 对象原始数组,我得到相同的结果:
dt = copy.deepcopy(arr.dtype)
arr.dtype = dt
arr3.dtype.names = ('g','h')
arr.dtype.names
--> ('g','h')
I am trying to copy a recarray and change the names of the fields/records in the new array. However, this modifies the names of the original array (the values are not unlinked, however). Example:
import numpy as np
import copy
define original array
arr = np.array(np.random.random((3,2)),
dtype=[('a','float'),('b','float')])
first copy
arr2 = arr.copy()
arr2.dtype.names = ('c','d')
arr.dtype.names
--> ('c','d')
second copy
arr3 = copy.deepcopy(arr2)
arr2.dtype.names = ('e','f')
arr.dtype.names
--> ('e','f')
Why does this happen and how to keep this from happening? I suspect the dtype
is a separate list/object whose reference is copied upon copy()
, but even if I assign a deep copy of the dtype
object to the original array, I get the same result:
dt = copy.deepcopy(arr.dtype)
arr.dtype = dt
arr3.dtype.names = ('g','h')
arr.dtype.names
--> ('g','h')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我解释你的问题是你想让 arr3 有自己的数据类型,这样你就可以修改它而不影响原始数据类型。如果是这样,你可以
欺骗似乎我在创建 arr3 时必须具有不同的 dtype (更改 dt3,然后创建 arr3)。否则, ndarray 会获取预先存在的数据类型(这似乎是某种代理)。
事实上,我之前也曾遇到过类似的问题,但没有找到。然后我想修改部分 dtype,但不知道如何,所以我最终再次硬连接了第二个 dtype 的整个定义(我的一个字段是子数组,我只在运行时知道它的形状)。所以这对我来说是个好问题:)
I intepret your Q that you want to have arr3 to have its own dtype, so that you can modify it without affecting dtype of original one. if so, you can
Trick seems that I have to have different dtype when I create arr3 (changed dt3, then create arr3). otherwise, ndarray grabs pre-existing dtype (this seems some kind of proxy).
Actually I struggled with similar problem earlier without finding it. I wanted modify part of dtype then, but didnt know how so i ended up hard-wired entire definition again for this second dtype (one field of mine was sub-array and i know its shape only at runtime). So this was good Q for me :)