pythonarraysnumpymatrixtriangular

sort elements from 1d array into triangular matrix


I am trying to move the elements from 1d array (55,) made up of

array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3,
       4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4,
       5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1]).

I want to organize this 1d array into a formation like the following:

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0],
 [0, 0],
 [0]]

so I want to end up with this:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4],
 [1, 2, 3],
 [1, 2],
 [1]]

What is the most efficient way to do this? Also note that I want to do this for a large array of 325K elements to organize it into 807 distinct rows.


Solution

  • If you know exactly how many items you want in your first row you can do this

    import numpy as np
    
    a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3,
           4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4,
           5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1])
    
    b = []
    index = 0
    
    for i in range(10, 0, -1):
        b.append(a[index:index+i])
        index += i
    
    for j in b:
        print(j)
    

    which will output this

    [1 2 3 4 5 6 7 8 9 0]
    [1 2 3 4 5 6 7 8 9]
    [1 2 3 4 5 6 7 8]
    [1 2 3 4 5 6 7]
    [1 2 3 4 5 6]
    [1 2 3 4 5]
    [1 2 3 4]
    [1 2 3]
    [1 2]
    [1]