python - sort 3D array by the sum of the second value -
i'm trying sort 3d array , having little success. have read various methods on how done 2 dimensions, can't seem scale up.
i have array like:
[[[0, 25], [1, 20], [2, 80], [0, 0], [0, 0], [0, 0]], [[0, 80], [0, 20], [1, 25], [1, 40], [2, 99], [0, 0]], [[0, 99], [1, 40], [2, 80], [0, 0], [0, 0], [0, 0]]]
i want sorted sum of second value. criteria use order sum of second value. e.g:
25+20+80 = 125 80+20+25+40+99 = 264 99+40+80 = 219
so:
[[[0, 80], [0, 20], [1, 25], [1, 40], [2, 99], [0, 0]], [[0, 99], [1, 40], [2, 80], [0, 0], [0, 0], [0, 0]]], [[0, 25], [1, 20], [2, 80], [0, 0], [0, 0], [0, 0]]]
could me ?
i think understand need. suppose array stored in a
.
>>> out[19]: array([[[ 0, 25], [ 1, 20], [ 2, 80], [ 0, 0], [ 0, 0], [ 0, 0]], [[ 0, 80], [ 0, 20], [ 1, 25], [ 1, 40], [ 2, 99], [ 0, 0]], [[ 0, 99], [ 1, 40], [ 2, 80], [ 0, 0], [ 0, 0], [ 0, 0]]])
a[:, :, 1]
accesses second element of innermost dimension, can sum on (on horizontal axis, i.e. axis=1) values need sorting:
>>> a[:, :, 1] out[20]: array([[25, 20, 80, 0, 0, 0], [80, 20, 25, 40, 99, 0], [99, 40, 80, 0, 0, 0]]) >>> b = np.sum(a[:, :, 1], axis=1) >>> b out[21]: array([125, 264, 219])
use np.argsort
sorted indices, rather sorted array:
>>> = np.argsort(b)[::-1] # reverse array descending order >>> out[23]: array([1, 2, 0])
finally, access array using indices, desired:
>>> a[i, :, :] out[25]: array([[[ 0, 80], [ 0, 20], [ 1, 25], [ 1, 40], [ 2, 99], [ 0, 0]], [[ 0, 99], [ 1, 40], [ 2, 80], [ 0, 0], [ 0, 0], [ 0, 0]], [[ 0, 25], [ 1, 20], [ 2, 80], [ 0, 0], [ 0, 0], [ 0, 0]]])
hope helps!
Comments
Post a Comment