SzJYn6Qg
SzJYn6Qg

Reputation: 31

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.

Upvotes: 3

Views: 1449

Answers (1)

hpaulj
hpaulj

Reputation: 231530

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)

Upvotes: 8

Related Questions