0

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.

3
  • 3
    Have you tried np.insert? Commented Apr 17, 2018 at 10:24
  • 3
    Particularly, np.insert([1, 2, 3, 4], [0, 1, 3], 0) is [0, 1, 0, 2, 3, 0, 4] (see docs). Commented Apr 17, 2018 at 10:26
  • It works, thank you. Commented Apr 17, 2018 at 10:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.