python - getting the opposite diagonal of a numpy array -
so in numpy arrays there built in function getting diagonal indices, can't seem figure out how diagonal starting top right rather top left.
this normal code starting top left:
>>> import numpy np >>> array = np.arange(25).reshape(5,5) >>> diagonal = np.diag_indices(5) >>> array array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) >>> array[diagonal] array([ 0, 6, 12, 18, 24])
so use if want return:
array([ 4, 8, 12, 16, 20])
there
in [47]: np.diag(np.fliplr(array)) out[47]: array([ 4, 8, 12, 16, 20])
or
in [48]: np.diag(np.rot90(array)) out[48]: array([ 4, 8, 12, 16, 20])
of two, np.diag(np.fliplr(array))
faster:
in [50]: %timeit np.diag(np.fliplr(array)) 100000 loops, best of 3: 4.29 per loop in [51]: %timeit np.diag(np.rot90(array)) 100000 loops, best of 3: 6.09 per loop
Comments
Post a Comment