Home > Mobile >  how to repeat values at certain indicies twice in a numpy array
how to repeat values at certain indicies twice in a numpy array

Time:04-07

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 ]

CodePudding user response:

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]

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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!

  • Related