one of a kind scene

[python] 데이터 프레임 정렬 및 정렬 후 index reset하기 본문

Python/데이터 핸들링

[python] 데이터 프레임 정렬 및 정렬 후 index reset하기

specialscene 2019. 12. 10. 23:51

(언제 사용?)

데이터 프레임을 특정 칼럼을 기준으로 정렬하게되면 index를 reset해줄 필요가 있기때문에

정렬방법과 index를 reset하는 방법을 알아야함

 

(예시 코드)

# 1) 내림차순으로 정렬하기 
''' 
axis = 0 하면 세로방향으로 있는 데이터 정렬(우리가 흔히 쓰는거) 따라서 by = '칼럼이름'
axis = 1 하면 가로방향으로 있는 데이터 정렬 따라서 by = 'row번호'
'''
# ascending=False 하면 내림차순
df = df.sort_values(by=['칼럼1'], axis=0, ascending = False)

# 2) index reset하기
df = df.reset_index(drop=True)

 

(참고 url)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html