Pandas: 인덱스와 열을 기준으로 dataframe 정렬


다음 구문을 사용하여 pandas DataFrame을 인덱스와 열별로 정렬할 수 있습니다.

 df = df. sort_values (by = [' column_name ', ' index '], ascending = [ False , True ])

다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.

예: 인덱스와 열을 기준으로 DataFrame 정렬

다음 코드는 pandas DataFrame을 points 라는 열을 기준으로 정렬한 다음 인덱스 열을 기준으로 정렬하는 방법을 보여줍니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' id ': [1, 2, 3, 4, 5, 6, 7, 8],
                   ' points ': [25, 15, 15, 14, 20, 20, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}). set_index (' id ')

#view first few rows
df. head ()

	points assists rebounds
id			
1 25 5 11
2 15 7 8
3 15 7 10
4 14 9 6
5 20 12 6

#sort by points and then by index
df. sort_values (by = [' points ', ' id '], ascending = [ False , True ])

	points assists rebounds
id			
8 29 4 12
1 25 5 11
7 25 9 9
5 20 12 6
6 20 9 5
2 15 7 8
3 15 7 10
4 14 9 6

결과 DataFrame은 포인트별로 내림차순으로 정렬된 다음 인덱스별로 오름차순으로 정렬됩니다(동일한 포인트를 획득한 두 명의 플레이어가 있는 경우).

오름차순 인수를 사용하지 않으면 각 열은 기본 정렬 방법으로 오름차순을 사용합니다.

 #sort by points and then by index
df. sort_values (by = [' points ', ' id '])

        points assists rebounds
id			
4 14 9 6
2 15 7 8
3 15 7 10
5 20 12 6
6 20 9 5
1 25 5 11
7 25 9 9
8 29 4 12

현재 인덱스 열의 이름이 지정되지 않은 경우 이름을 바꾼 다음 그에 따라 정렬할 수 있습니다.

 #sort by points and then by index
df. rename_axis (' index '). sort_values (by = [' points ', ' id '])

        points assists rebounds
id			
4 14 9 6
2 15 7 8
3 15 7 10
5 20 12 6
6 20 9 5
1 25 5 11
7 25 9 9
8 29 4 12

추가 리소스

Pandas: 이름별로 열을 정렬하는 방법
Pandas: 날짜별로 DataFrame 정렬
Pandas: 중복 행을 제거하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다