enden
enden

Reputation: 163

numpy array to triangle (matrix)

I have an array that I want split int a matrix (10x10). after a several tries i did this.

a=np.arange(1,56)
tri = np.zeros((10, 10))
tri[np.triu_indices_from(tri,0)]=a
tri

array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.],
       [  0.,  11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.],
       [  0.,   0.,  20.,  21.,  22.,  23.,  24.,  25.,  26.,  27.],
       [  0.,   0.,   0.,  28.,  29.,  30.,  31.,  32.,  33.,  34.],
       [  0.,   0.,   0.,   0.,  35.,  36.,  37.,  38.,  39.,  40.],
       [  0.,   0.,   0.,   0.,   0.,  41.,  42.,  43.,  44.,  45.],
       [  0.,   0.,   0.,   0.,   0.,   0.,  46.,  47.,  48.,  49.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,  50.,  51.,  52.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  53.,  54.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  55.]])

and the result I wish:

array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.],
       [  11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  0.],  
       [  20.,  21.,  22.,  23.,  24.,  25.,  26.,  27.,  0.,   0.],
       [  28.,  29.,  30.,  31.,  32.,  33.,  34.,  0.,   0.,   0.],
       [  35.,  36.,  37.,  38.,  39.,  40.,  0.,   0.,   0.,   0.],
       [  41.,  42.,  43.,  44.,  45.,  0.,   0.,   0.,   0.,   0.],
       [  46.,  47.,  48.,  49.,  0.,   0.,   0.,   0.,   0.,   0.],
       [  50.,  51.,  52.,  0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  53.,  54.,  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  55.,  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])

I did several ties like try.T, np.triu, np.tril ...etc.

thanks

Upvotes: 3

Views: 1358

Answers (1)

akuiper
akuiper

Reputation: 214957

If this is what you mean, you can rotate an upper triangular index matrix by 90 degree using rot90() method and then use it as index to fill the values in the array:

import numpy as np
a=np.arange(1,56)
tri = np.zeros((10, 10))
tri[np.rot90(np.triu(np.ones((10,10), dtype=bool)))] = a

tri
# array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.],
#        [ 11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,   0.],
#        [ 20.,  21.,  22.,  23.,  24.,  25.,  26.,  27.,   0.,   0.],
#        [ 28.,  29.,  30.,  31.,  32.,  33.,  34.,   0.,   0.,   0.],
#        [ 35.,  36.,  37.,  38.,  39.,  40.,   0.,   0.,   0.,   0.],
#        [ 41.,  42.,  43.,  44.,  45.,   0.,   0.,   0.,   0.,   0.],
#        [ 46.,  47.,  48.,  49.,   0.,   0.,   0.,   0.,   0.,   0.],
#        [ 50.,  51.,  52.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
#        [ 53.,  54.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
#        [ 55.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])

Upvotes: 2

Related Questions