Suppose I have an array (not necessarily square)
my_array = ['name_1', 3
'name_2', 2]
and I want to end up with an list (or numpy array etc) of length 3+2=5
where the first three positions are assigned to 'name_1'
and the next 2 to 'name_2'
. Hence the output will be
['name_1', 'name_1', 'name_1', 'name_2', 'name_2']
This is what I have done so far; Is there a better way to do this please?
import numpy as np
my_array = np.array([['name_1', 3], ['name_2', 2]])
l = []
for i in range(my_array.shape[0]):
x = [my_array[i, 0].tolist()] * np.int(my_array[i, 1])
l.append(x)
flat_list = [item for sublist in l for item in sublist]
print(flat_list)
which prints:
['name_1', 'name_1', 'name_1', 'name_2', 'name_2']
Thanks!
Use np.repeat
:
my_array[:,0].repeat(my_array[:,1].astype(int))
# array(['name_1', 'name_1', 'name_1', 'name_2', 'name_2'], dtype='<U6')
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