简体   繁体   中英

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. 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 :

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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