Say I have a square numpy.matrix like this
[['78' '17' '53' '28']
['22' '75' '31' '67']
['15' '94' '03' '80']
['04' '62' '16' '14']]
and for my purposes I need a "diamond structure" like this of all of the diagonals in an upwards direction (note that a list of lists is fine for my purpose)
[ ['78'],
['22' '17'],
['15' '75' '53'],
['04' '94' '31' '28'],
['62' '03' '67'],
['16' '80'],
['14'], ]
What is the best way to do so?
I can't decide if using some incrementing magic with position accessing is required or some built in way making use of numpy.diagonal is possible, which I haven't been able to employ successfully yet.
import numpy as np
a=np.array([[78, 17, 53, 28],
[22, 75, 31, 67],
[15, 94, 03, 80],
[04, 62, 16, 14]])
[np.diag(a[-1:-a.shape[0]-1:-1,:], i).tolist() for i in range(-a.shape[0]+1,a.shape[0])]
outputs [[78], [22, 17], [15, 75, 53], [4, 94, 31, 28], [62, 3, 67], [16, 80], [14]] as requested
it works very fast for 1000x1000 matrix as well
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