akilat90
akilat90

Reputation: 5696

Repeating numpy array elements according to another index array

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])

Upvotes: 1

Views: 334

Answers (2)

HYRY
HYRY

Reputation: 97261

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)

Upvotes: 3

cs95
cs95

Reputation: 402323

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])

Upvotes: 3

Related Questions