how do I concatenate the results of a concatenated array?

Viewed 18

I have two matrices (dfs):

A = [1 2 3 4
     5 6 7 8 
     9 10 11 12]

and B = [1, 2, 3]

and I want matrix C to be repeating each row in A, B times. for example, first row, 1,2,3,4 needs to be repeated once, second row: 5,6,7,8 twice and last row three times:

C = [1 2 3 4
     5 6 7 8
     5 6 7 8 
     9 10 11 12
     9 10 11 12
     9 10 11 12]

my code

for i in range(0,2401):
    g = pd.concat([df1.iloc[[i]]]*z[i], ignore_index=True)

partially does this, except only gives me the 3 times last row part, I need to concatenate each concatenation.

below gives me what I want but its not clean, i.e. indices are not ignored and messy.

result = []
for i in range(0,2401):
    g = pd.concat([df1.iloc[[i]]]*z[i], ignore_index=True)
    result.append(g)
1 Answers

If you write your matrices like:

A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
B = [1, 2, 3]
C = []

You can iterate through B and add to C like:

for i in range(len(B)):
    index = 0
    while index < B[i]:
        C.append(A[i])
        index += 1

Which has an output:

[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [5, 6, 7, 8],
 [9, 10, 11, 12],
 [9, 10, 11, 12],
 [9, 10, 11, 12]]

I hope this helps!

Related