简体   繁体   English

如何使numpy数组可变?

[英]How to make numpy array mutable?

packed_bytes = resources[bv.byteOffset : bv.byteOffset + bv.byteLength]

arr = np.frombuffer(
    packed_bytes,
    dtype=component_type[accessor.componentType].replace("{}", ""),
).reshape((-1, accessor_type[accessor.type]))
arr.flags.writeable = True # this does not work

It gives:它给:

ValueError: cannot set WRITEABLE flag to True of this array

When trying to set writeable flag to the numpy array.尝试将可写标志设置为 numpy 数组时。 Before adding that line of code, it gave:在添加那行代码之前,它给出了:

ValueError: output array is read-only

When trying to write to the array.尝试写入数组时。 Any ideas on how to fix this?有想法该怎么解决这个吗? I have no idea why this is an issue.我不知道为什么这是一个问题。

Using an example from frombuffer :使用frombuffer的示例:

x=np.frombuffer(b'\x01\x02', dtype=np.uint8)

x
Out[105]: array([1, 2], dtype=uint8)

x.flags
Out[106]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : False
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

x[0]=3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [107], in <cell line: 1>()
----> 1 x[0]=3

ValueError: assignment destination is read-only

The buffer is a bytestring.缓冲区是一个字节串。 Python strings are not mutable, so the resulting array isn't either. Python 字符串是不可变的,因此结果数组也不可变。

with bytearray带字节数组

x=np.frombuffer(bytearray(b'\x01\x02'), dtype=np.uint8)

x.flags
Out[112]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

x[0]=3

x
Out[114]: array([3, 2], dtype=uint8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM