16 Sort

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)
       Irizona    Qoston   Zhicago   Betroit
2004  0.151643  0.807621  2.107269  0.598419
1999  0.440249 -0.650256 -1.129791 -1.090008
2020  0.600021 -1.130344 -0.391722  0.620353
In [84]:
# 컬럼을 기준을 세로 정렬
df.sort_values('Betroit', ascending=True)
df.sort_values('Betroit') # True 인 경우에는 ascending=True를 생략할 수 있음 
Out[84]:
IrizonaQostonZhicagoBetroit
19990.440249-0.650256-1.129791-1.090008
20040.1516430.8076212.1072690.598419
20200.600021-1.130344-0.3917220.620353
In [87]:
# 두개의 컬럼을 정렬
df.sort_values(['Qoston','Betroit'],ascending= [0, 1])
Out[87]:
IrizonaQostonZhicagoBetroit
20040.1516430.8076212.1072690.598419
19990.440249-0.650256-1.129791-1.090008
20200.600021-1.130344-0.3917220.620353
In [53]:
# index를 축으로 세로 방향으로 정렬 수 있음
df.sort_values(2020, ascending=True, axis = 1)
Out[53]:
QostonIrizonaZhicagoBetroit
20040.8957740.5840620.9886970.171808
19990.6205120.6665680.0985560.656940
20200.2818860.4776480.4962500.696297
In [95]:
# Index 객체내에 sort_value가 존재하여 colunm이나 index를 정렬 할 수 있음
print(df.columns.sort_values())
df.index.sort_values()
Index(['Betroit', 'Irizona', 'Qoston', 'Zhicago'], dtype='object')
Out[95]:
Int64Index([1999, 2004, 2020], dtype='int64')
In [97]:
# sort_index는 인덱스 레벨을 정렬할 수 있음
df.sort_index()
Out[97]:
IrizonaQostonZhicagoBetroit
19990.440249-0.650256-1.129791-1.090008
20040.1516430.8076212.1072690.598419
20200.600021-1.130344-0.3917220.620353
In [98]:
#sort_index에 axis =1을 추가하면 가로 방향으로 컬럼 레벨을 정렬할 수 있음
df.sort_index(axis = 1)
Out[98]:
BetroitIrizonaQostonZhicago
20040.5984190.1516430.8076212.107269
1999-1.0900080.440249-0.650256-1.129791
20200.6203530.600021-1.130344-0.391722


© 2017. All rights reserved.

Powered by ZooFighter v0.12