Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a specific value in a list/array?

Any advice on how to repeat a certain value in an array in Python? For instance, I want to repeat only 2 in array_a:

array_a = [1, 2, 1, 2, 1, 1, 2]

Wanted outcome is: I repeat each 2 and leave the 1:

array_a = [1, 2, 2, 1, 2, 2, 1, 1, 2, 2]  # only the `2` should be repeated

I tried numpy and I could duplicate the entire array but not a certain value.

like image 806
As tudent Avatar asked Sep 13 '18 23:09

As tudent


People also ask

Can you have duplicate values in a list Python?

Python list can contain duplicate elements.

How do you copy part of an array in Python?

ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].

Can there be duplicate elements in a list?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.


1 Answers

If you're interested in a numpy solution, you can repeat an array on itself using np.repeat.

>>> import numpy as np
>>> np.repeat(array_a, array_a)
array([1, 2, 2, 1, 2, 2, 1, 1, 2, 2])

This works only if you haves 1s and 2s in your data. For a generic solution, consider

>>> n_repeats = 2
>>> temp = np.where(np.array(array_a) == 2, n_repeats, 1)
>>> np.repeat(array_a, temp)
array([1, 2, 2, 1, 2, 2, 1, 1, 2, 2])
like image 88
cs95 Avatar answered Nov 03 '22 01:11

cs95