'how to repeat values at certain indicies twice in a numpy array
I have this numpy array:vals = numpy.array([10,20,30,40,50])ind = numpy.array([0,3,4])
I want to duplicate twice each value in vals at each index in ind so the result would be:res = [ 10 10 20 30 40 40 50 50 ]
Solution 1:[1]
A neat way to produce the desired result would be to use numpy.insert:
vals = numpy.array([10,20,30,40,50])
ind = numpy.array([0,3,4])
res = list(numpy.insert(vals, ind, vals[ind]))
print(res)
Output:
[10, 10, 20, 30, 40, 40, 50, 50]
Solution 2:[2]
In [2]: vals = numpy.array([10,20,30,40,50])
...: ind = numpy.array([0,3,4])
Build a repetition array like:
In [3]: reps = np.ones(vals.shape[0], int)
In [4]: reps[ind]+=1
In [5]: reps
Out[5]: array([2, 1, 1, 2, 2])
In [6]: np.repeat(vals,reps)
Out[6]: array([10, 10, 20, 30, 40, 40, 50, 50])
Solution 3:[3]
i don't know how to do this in a vectorized way, but you could just write a function to do it:
def dupe_at_indices(array, indices):
for i, v in enumerate(array):
yield v
if i in indices:
yield v
res = list(dupe_at_indices(vals, set(ind)))
Solution 4:[4]
Well I did what i knew, so here is my answer.
import numpy
vals = numpy.array([10,20,30,40,50])
ind = numpy.array([0,3,4])
x = ""
for i in ind:
x += str(vals[i]) + " " + str(vals[i]) + " "
print("[" + x + "]")
You may be confused about "[" and "]", sorry but this is what i can do now, at least it is doing what you wanted, good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | frederic |
| Solution 2 | hpaulj |
| Solution 3 | acushner |
| Solution 4 | Lack_of_experience |
