개발공부

[Python] Pandas 데이터 정렬하기 sort_values(), sort_index() 본문

Python/Pandas

[Python] Pandas 데이터 정렬하기 sort_values(), sort_index()

mscha 2022. 5. 3. 14:05
import pandas as pd

df = pd.DataFrame({'Employee ID':[111, 222, 333, 444], 
                   'Employee Name':['Chanel', 'Steve', 'Mitch', 'Bird'], 
                   'Salary [$/h]':[35, 29, 38, 20], 
                   'Years of Experience':[3, 4 ,9, 1]})
df

sort_index()

인덱스에 기반하여 정렬한다.

# ascending = True면 오름차순, False면 내림차순
df.sort_index()

 

sort_values()

데이터에 기반하여 정렬한다.

# 경력을 오름차순으로 정렬
df.sort_values('Years of Experience')

# 경력을 내림차순으로 정렬
df.sort_values('Years of Experience', ascending = False)

#이름과 경력으로 정렬하되,
# 이름은 내림차순, 경력은 오름차순으로 정렬
# 여러개에 대해서 정렬 할 때는 리스트로 정리한다.
df.sort_values(['Employee Name', 'Years of Experience'], ascending = [False, True])