16 Sort
| 5 Minute Read on Pandas
Sort¶
Pandas에서는 sort_values메소드를 사용하여 columns과 index(row) 별로 정렬할 수 있다. Sort_Values Docs
- index(row)로 정렬 할 경우에는 sort_values에 추가적으로 axis = 1가 필요하다.
- 컬럼이 2개인 인상인 경우에는 다음과 형태로 표현한다. df.sort(['A', 'B'], ascending=[1, 0])
sort_index를 사용하여 index의 label을 정렬할 수 있다.Sort_Index
- 축이 세로 방향인 index level을 정렬할 경우에는 axis가 필요없지만 축이 가로 방향인 column level 을 정렬할 경우에는 axis = 0가 필요하다.
In [63]:
import pandas as pd
import numpy as np
data = np.random.randn(3,4)
#로 표현 할 수 있음
index = [2004, 1999, 2020 ]
columns = ['Irizona','Qoston', 'Zhicago','Betroit']
df = pd.DataFrame(data = data, index = index , columns = columns)
print(df)
In [84]:
# 컬럼을 기준을 세로 정렬
df.sort_values('Betroit', ascending=True)
df.sort_values('Betroit') # True 인 경우에는 ascending=True를 생략할 수 있음
Out[84]:
In [87]:
# 두개의 컬럼을 정렬
df.sort_values(['Qoston','Betroit'],ascending= [0, 1])
Out[87]:
In [53]:
# index를 축으로 세로 방향으로 정렬 수 있음
df.sort_values(2020, ascending=True, axis = 1)
Out[53]:
In [95]:
# Index 객체내에 sort_value가 존재하여 colunm이나 index를 정렬 할 수 있음
print(df.columns.sort_values())
df.index.sort_values()
Out[95]:
In [97]:
# sort_index는 인덱스 레벨을 정렬할 수 있음
df.sort_index()
Out[97]:
In [98]:
#sort_index에 axis =1을 추가하면 가로 방향으로 컬럼 레벨을 정렬할 수 있음
df.sort_index(axis = 1)
Out[98]: