python
다차원 ndarray 를 정렬하는 방법
BetterToday
2017. 8. 16. 23:12
728x90
numpy 에서 제공하는 data structure 인 ndarray 를 특정 dimension 에 따라 정렬하는 법을 정리한다.
1. 문제상황
(n, m) shape 의 2차원 array 가 있을 때 column index 별로 정렬하고 싶을 때가 있다.
위 그림처럼 (10, 3) shape 의 array 에서 column index [0, 1, 2] 별로 정렬하는 방법을 알아보자.
2. Python Code
2.1 Python Code
import numpy as np
data = np.random.randn(10, 3)
data = data[data[:, 0].argsort()[::-1]]
print data
data = data[data[:, 1].argsort()[::-1]]
print data
data = data[data[:, 2].argsort()[::-1]]
print data
2.2 실행결과
[[ 1.6173823 -1.13007304 0.18074012]
[ 1.33285661 -1.94595392 0.93933421]
[ 0.34035015 0.32793116 -0.11886106]
[ 0.21158198 0.92927337 0.54823083]
[-0.32346608 -0.41573029 0.21032649]
[-0.39041094 0.28947627 -1.34514867]
[-0.491294 -0.02294494 1.30686972]
[-0.57466536 -0.72987815 -0.20252056]
[-0.83532394 -0.16538848 -2.08268926]
[-1.39983016 -0.55943045 -0.75066581]]
[[ 0.21158198 0.92927337 0.54823083]
[ 0.34035015 0.32793116 -0.11886106]
[-0.39041094 0.28947627 -1.34514867]
[-0.491294 -0.02294494 1.30686972]
[-0.83532394 -0.16538848 -2.08268926]
[-0.32346608 -0.41573029 0.21032649]
[-1.39983016 -0.55943045 -0.75066581]
[-0.57466536 -0.72987815 -0.20252056]
[ 1.6173823 -1.13007304 0.18074012]
[ 1.33285661 -1.94595392 0.93933421]]
[[-0.491294 -0.02294494 1.30686972]
[ 1.33285661 -1.94595392 0.93933421]
[ 0.21158198 0.92927337 0.54823083]
[-0.32346608 -0.41573029 0.21032649]
[ 1.6173823 -1.13007304 0.18074012]
[ 0.34035015 0.32793116 -0.11886106]
[-0.57466536 -0.72987815 -0.20252056]
[-1.39983016 -0.55943045 -0.75066581]
[-0.39041094 0.28947627 -1.34514867]
[-0.83532394 -0.16538848 -2.08268926]]
728x90
반응형