1

I have the following placeholder array:

placeholder = np.zeros(10)

A contains the values that I want to go in to the placeholder

A = np.array([25, 40, 65,50])

idx has the indices of the placeholder ( note that this has the same shape as A)

idx = np.array([0, 5, 6, 8])

Question:

I want placeholder to be populated with the elements of A. The amount to which an element in A to be repeated is defined by the length of the intervals of the idx array.

For example, 25 is repeated 5 times because the corresponding index range is [0, 5). 65 is repeated twice because the corresponding index range is [6,8)

Expected output:

np.array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])

2 Answers 2

3

Quick and easy, using np.diff + np.repeat:

repeats = np.diff(np.append(idx, len(placeholder)))

A.repeat(repeats)
array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to use placeholder array:

import numpy as np

placeholder = np.zeros(10)
A = np.array([25, 40, 65,50])
idx = np.array([0, 5, 6, 8])

placeholder[idx[0]] = A[0]
placeholder[idx[1:]] = np.diff(A)    
np.cumsum(placeholder, out=placeholder)

1 Comment

This solution is out of this world! Unfortunately, I had to accept the other one because of it's readability.

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.