David Masip
David Masip

Reputation: 2491

Adding zeros to given positions in a numpy array

I have a numpy array and I want a function that takes as an input the numpy array and a list of indices and returns as an output another array which has the following property: a zero has been added to the initial array just before the position of each of the indices of the origional array.

Let me give a couple of examples:

If indices = [1] and the initial array is array([1, 1, 2]), then the output of the function should be array([1, 0, 1, 2]).

If indices = [0, 1, 3] and the initial array is array([1, 2, 3, 4]), then the output of the function should be array([0, 1, 0, 2, 3, 0, 4]).

I would like to do it in a vectorized manner without any for loops.

Upvotes: 0

Views: 1386

Answers (1)

tda
tda

Reputation: 2133

Had the same issue before. Found a solution using np.insert:

import numpy as np
np.insert([1, 1, 2], [1], 0)

>>> [1, 0, 1, 2]

I see @jdehesa has commented this already but adding as a permanent answer for future visitors.

Upvotes: 2

Related Questions