Pandas DataFrame을 색인별로 정렬하는 방법은 무엇입니까?


91

다음과 같은 DataFrame이있는 경우 :

import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])

인덱스와 열 값의 각 조합을 그대로 유지하면서 인덱스별로이 데이터 프레임을 정렬하려면 어떻게해야합니까?

답변:


149

데이터 프레임에는 sort_index기본적으로 복사본을 반환 하는 메서드가 있습니다. inplace=True제자리에서 작동하려면 통과하십시오 .

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

나에게 제공 :

     A
1    4
29   2
100  1
150  5
234  3

13

약간 더 콤팩트 :

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

노트 :


9
.sort()문서화 문자열은 말한다DEPRECATED: use DataFrame.sort_values()
endolith

1
@endolith Indeed .sort()는 이후 더 이상 사용되지 않습니다. 대체는 .sort_index()Paul H가 그의 답변에서 사용하는 것과 같으며,이 경우 답변 간의 유일한 차이점은 I do n't use inplace=True입니다.
fantabolous
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.