I have below code that allows me to iterate over a flattened list and maps the updates back to the structured array -
a = np.asarray([1,2,3])
b = np.asarray([4,5,6])
c = np.asarray([a, b])
print c
r = c.ravel()
print r
r[1] = 10
print c
setting r[1] = 10 modifies c[0][1] to 10. I want to do something similar with the lower snippet but this fails and I am assuming it's because the dimensions are inconsistent. Is there some way to get similar behavior so I can modify a flattened version without having to reshape it back to c?
a = np.asarray([1,2,3])
b = np.asarray([4,5,6,7,8])
c = np.asarray([a, b])
r = c.ravel()
r[1] = 10
print r
In your first case
c
is a 2d arrayravel
produces a view ofc
, so changes to one appear in the otherYou can also index
c
withflat
, with the same effect:These changes to
c
orr
do not affect the originala
orb
.asarray
copies those arrays.In the second case
c
is a 1d array containing other arrays:The pieces can be joined into a 1d array:
Values can be changed, but won't affect the original
c
.This changes the original
a
becausec
literally containsa
, not a copy of it:np.array
(orasarray
) tries to make as-a-dimensional array as it can from the inputs. In the first case inputs are equal in size, so it makes a 2d. In the second they differ so it makes a 1d array of objects. This behavior often gives users problems. Either they expect a 2d array in the second case, or they can't produce the object array in the first.To reliably make an object array, regardless of whether the inputs match in size or not, you have to do something like