Code/Python

[Python]DataFrame 정렬, sort_values() / sort_index(), 다중 정렬

heedy 2022. 11. 2. 14:03
728x90

DataFrame을 Data 기준에 대해 알아보겠습니다.


- sort_values()

titanic 데이터를 load 해줍니다.

import pandas as pd

# data load

df = pd.read_csv('train.csv')

Pclass 기준으로 데이터를 정렬합니다.
option으로 by를 사용하여 기준 컬럼을 설정할 수 있습니다.

df.sort_values(by = 'Pclass')

오름차순 정렬

Pclass 기준으로 오름차순 정렬이 됐습니다.

Pclass 기준으로 내림차순 정렬을 하겠습니다.
ascending = False로 설정하여 내림차순을 할 수 있습니다.

df.sort_values(by = 'Pclass', ascending = False)

내림차순 정렬

- 다중 정렬

by option을 통해 다중 정렬도 가능합니다.

Fare를 기준으로 오름차순 정렬 후 Pclass를 기준으로 내림차순 정렬해보겠습니다.
리스트로 묶어 option을 설정할 시 차례대로 정렬이 되며, 오름차순 / 내림차순도 다중으로 설정가능합니다.
Fare에서 먼저 정렬된 후 Pclass가 정렬이 되는 것을 확인 할 수 있습니다.

df.sort_values(by = ['Fare','Pclass'], ascending = [True, False])

다중 정렬


- sort_index()

index를 기준으로 정렬합니다.

df.sort_index()

index 기준 정렬

index를 기준으로 내림차순 정렬합니다.
sort_values()와 동일하게 ascending = False option을 통해 설정할 수 있습니다.

df.sort_index(ascending = False)

index 기준 내림차순 정렬

728x90