Python numpy에서 numpy.argsort()
를 이용하여 배열을 정렬할 수 있습니다.
다양한 예제와 함께 알아보겠습니다.
1. 오름차순으로 배열 정렬
numpy.argsort(arr)
은 배열 arr을 정리하고 정렬된 Index 배열을 리턴합니다.
- Index 배열은, 정렬된 배열의 값이 실제 배열에서 위치하고 있는 Index를 의미
arr[sorted_index]
는 오름차순으로 정렬된 배열 리턴
import numpy as np
arr = np.array([3, 1, 4, 2, 5])
sorted_index = np.argsort(arr)
sorted_arr = arr[sorted_index]
print("arr:", sorted_arr)
print("index:", sorted_index)
위 코드 실행 결과를 보면, 정렬된 배열의 0번 Index는 1이고, 1은 실제 배열에서 Index 1에 위치해있습니다. 따라서 Index 배열에서 Index 0은 1의 값을 갖게 됩니다.
arr: [1 2 3 4 5]
index: [1 3 0 2 4]
2. 내림차순으로 배열 정렬
오름차순으로 정렬된 배열에 [::-1]
를 사용하여 순서를 뒤집으면 내림차순으로 정렬된 배열을 얻을 수 있습니다.
import numpy as np
arr = np.array([3, 1, 4, 2, 5])
sorted_index = np.argsort(arr)
sorted_arr = arr[sorted_index]
reversed_arr = sorted_arr[::-1]
print("reversed arr:", reversed_arr)
Output:
reversed arr: [5 4 3 2 1]
3. dtype 데이터 정렬
dtype
으로 정의된 객체의 배열도 argsort()
로 정렬할 수 있습니다.
아래 예제에서 name-age
쌍을 dtype으로 정의하였습니다.
4개 데이터가 있는 배열을 argsort()
로 정렬하는데, order=('age', 'name')
은 age를 우선으로 정렬하고, age가 동일하면 name으로 정렬하라는 의미입니다.
import numpy as np
dt = np.dtype([('name', 'S10'), ('age', int)])
arr = np.array([('Alice', 25), ('Bob', 30), ('Charlie', 30), ('David', 35)], dtype=dt)
sorted_index = np.argsort(arr, order=('age', 'name'))
sorted_arr = arr[sorted_index]
print(sorted_arr)
Output:
[(b'Alice', 25) (b'Bob', 30) (b'Charlie', 30) (b'David', 35)]
Loading script...
Related Posts
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy의 min(), max() 함수 (최소, 최대 값)
- numpy.mean(), 배열 평균 계산
- numpy.log(), 로그 함수 사용 방법
- numpy.shape(), 배열 크기/형태/차원 확인
- numpy.sqrt(), 배열의 제곱근 계산
- numpy.zeros(), 0으로 채워진 배열 생성
- Python Numpy 버전 확인 방법
- numpy.argsort(), 배열 정렬
- numpy.clip(), 배열의 최대/최소 값 지정
- numpy.linspace(), 동일 간격 숫자 배열
- Numpy - random 모듈, 난수 배열 생성
- Numpy의 ndarray 사용 방법 알아보기
- numpy.transpose(), 전치 행렬 변환
- Numpy - where() 사용 방법
- Python - numpy.append(), 배열 추가
- Python numpy.random.choice(), 랜덤 샘플링
- Python numpy.reshape(), 배열 차원 변경
- Python numpy.sum(), 배열의 합
- Python numpy.unique(), 배열 중복 제거
- Python - json.dumps()로 JSON 출력하기
- Python - find() 문자 위치 찾기
- Python lower() 문자열 소문자로 변환
- Python upper() 문자열 대문자로 변환
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제