본문 바로가기
study📚/python

[python/파이썬] 데이터 전처리 - 정렬 sort_index(), sort_values()

by 스닝 2022. 7. 25.

정렬

1. sort_index()

  • sort_index() : 인덱스 값을 기준으로 데이터 정렬
import pandas as pd

df = pd.DataFrame({'a' : [2, 3, 2, 7, 4], 'b' : [2, 1, 3, 5, 3], 'c' : [1, 1, 2, 3, 5]})
df

#인덱스 기준 정렬
df.sort_index()

#내림차순일때는 ascending = False

df.sort_index(ascending = False

df

#결과를 저장하고 싶다면 inplace = True

df.sort_index(ascending = False, inplace = True)

df

-reset_index() : 기존 행 인덱스를 제거하고 인덱스를 데이터 열 추가

df.reset_index()

df

df.reset_index(drop = True)

reset_index를 사용한다면 인덱스가 새로 생성 된 걸 볼 수 있다. drop = True 옵션을 주면 기존의 인덱스였던 것을 drop하고 새로 만들어진다.

df.reset_index(drop = True, inplace = True
df

2. sort_values()

  • sort_values() : 데이터 값을 기준으로 데이터 정렬. 기본적으로 데이터 값은 오름차순으로 정렬되며, 만약 칼럼에 NaN(결측치)가 있다면 그 값은 맨 마지막에 위치한다.
df = pd.DataFrame({'a' : [2, 3, 2, 7, 4], 'b' : [2, 1, 3, 5, 3], 'c' : [1, 1, 2, 3, 5]})
df

-문제 : a열 기준으로 오름차순으로 정렬하기

#df.sort_values(by = '정렬의 기준이 되는 칼럼명')
df.sort_values(by = ['a'])

by=[]의 괄호 안에 내가 기준으로 설정하고 싶은 칼럼명을 적어주면 된다

df

df.sort_values(by = ['a'], inplace = True)

df

-문제 : a열 기준으로 내림차순 정렬

df.sort_values(by = ['a'], ascending = False)

-문제 : a, b열 기준으로 오름차순 정렬하기

df.sort_values(by = 'a', 'b'])

-문제 : a열 기준으로 오름차순 정렬한 이후, b열 기준으로 내림차순 정렬하기

df.sort_values(by = ['a','b'], ascending = [True, False])

df

df.sort_values(by = ['a', 'b'], ascending = [True, False], inplace = True)
df

df.reset_index(drop = True, inplace = True)

df

댓글