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.
Python list can contain duplicate elements.
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].
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With