Pandas에서 두 열을 바꾸는 방법(예제 포함)


다음 사용자 정의 함수를 사용하여 Pandas DataFrame에서 두 열의 위치를 바꿀 수 있습니다.

 def swap_columns (df, col1, col2):
    col_list = list ( df.columns )
    x, y = col_list. index (col1), col_list. index (col2)
    col_list[y], col_list[x] = col_list[x], col_list[y]
    df = df[col_list]
    return df

이 함수는 DataFrame에서 col1col2 열의 위치를 바꿉니다.

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

예: Pandas에서 두 열 바꾸기

다음과 같은 팬더 DataFrame이 있다고 가정합니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   ' points ': [18, 22, 19, 14, 14, 11, 20, 28],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print (df)

  team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7:28 4 12

“points” 열과 “bounces” 열의 위치를 바꾸는 swap_columns() 함수를 정의할 수 있습니다.

 #define function to swap columns
def swap_columns (df, col1, col2):
    col_list = list ( df.columns )
    x, y = col_list. index (col1), col_list. index (col2)
    col_list[y], col_list[x] = col_list[x], col_list[y]
    df = df[col_list]
    return df

#swap points and rebounds columns
df = swap_columns (df, ' points ', ' rebounds '):

#view updated DataFrame
print (df)

  team rebounds assists points
0 A 11 5 18
1 B 8 7 22
2 C 10 7 19
3 D 6 9 14
4 E 6 12 14
5 F 5 9 11
6 G 9 9 20
7:12 a.m. 4:28

“포인트” 및 “리바운드” 열은 서로 바뀌었지만 다른 모든 열은 동일한 위치에 유지되었습니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas: 열에서 특정 값의 발생 횟수를 계산하는 방법
Pandas: 열이 값과 일치하는 행의 인덱스 가져오기
Pandas: DataFrame에서 누락된 값을 계산하는 방법

의견을 추가하다

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