This is sample array;
I want it increase the frequency of each element by constant (taking 4 here);
[64,64,64,64, 45, 45, 45, 45, 56, 56, 56, 56, 67, 67, 67, 67, 78, 78, 78, 78, 12, 12, 12, 12, 112, 112, 112, 112, 232, 232, 232, 232]
Can anyone help me with this? Please it should not be hardcoded
CodePudding user response:
You can use np.repeat
to achieve this:
>>> a.repeat(4)
array([ 64, 64, 64, 64, 45, 45, 45, 45, 56, 56, 56, 56, 67,
67, 67, 67, 78, 78, 78, 78, 12, 12, 12, 12, 112, 112,
112, 112, 232, 232, 232, 232])
CodePudding user response:
If you know what the expanded frequency will be at the time when you create the array, you can use a list comprehension to expand it first:
import numpy as np
a_prime = [64, 45, 56, 67, 78, 12, 112, 232]
a = np.array([x for x in a for i in range(4)])
If you need to change the amount to expand it by, you could wrap this in a function:
def expand_frequency(lst, n):
return [x for x in lst for i in range(n)]
a = np.array(expand_frequency(a_prime, 4))
I'm not sure if this is quite what you are looking for, but it should serve as a starting point.