Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat values in a column based on another

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!

like image 364
Aenaon Avatar asked Jan 01 '23 08:01

Aenaon


1 Answers

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')
like image 180
cs95 Avatar answered Jan 11 '23 12:01

cs95