iamapc
iamapc

Reputation: 69

Python - replace and insert in array

Say I have a list:

lst = np.array([1,2,3,4])

I would want to replace the 3 with [5,6,7], so I get

lst = [1,2,5,6,7,4]

I tried:

lst[2] = [5,6,7]

but this will give me an error: setting an array element with a sequence

Upvotes: 0

Views: 2000

Answers (1)

BrenBarn
BrenBarn

Reputation: 251355

You can't change the size of a numpy array in-place. You'll need to "manually" create a new numpy array of the appropriate size by concatenating slices of your other two arrays:

>>> x = np.array([1,2,3,4])
>>> y = np.concatenate((x[:2], [5, 6, 7], x[3:]))
>>> y
array([1, 2, 5, 6, 7, 4])

Alternatively, you could convert your array to a list and do the replacement on the list:

>>> x = np.array([1,2,3,4])
>>> y = list(x)
>>> y[2:3] = [5, 6, 7]
>>> y = np.array(y)
>>> y
array([1, 2, 5, 6, 7, 4])

(Note that unlike an operation such as x[2] = 3, both of these options create a new independent array, rather than mutating x.)

Numpy arrays are not compatible with size-changing operations; the only way to do it is to make an entirely new array. If you need to change the size of objects, don't use numpy arrays; if you need to use numpy arrays, find a way to minimize or avoid changing their sizes.

Upvotes: 2

Related Questions