Pandas dataframe에서 열 순서를 변경하는 방법
다음 구문을 사용하여 Pandas DataFrame의 열 순서를 빠르게 변경할 수 있습니다.
df[[' column2 ', ' column3 ', ' column1 ']]
다음 예에서는 다음 Pandas DataFrame에서 이 구문을 사용하는 방법을 보여줍니다.
import pandas as pd #create new DataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #display DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
예시 1: 이름별로 열 순서 변경
다음 코드는 이름에 따라 DataFrame의 열 순서를 변경하는 방법을 보여줍니다.
#change order of columns by name
df[[' rebounds ', ' assists ', ' points ']]
rebound assists points
0 11 5 25
1 8 7 12
2 10 7 15
3 6 9 14
4 6 12 19
5 5 9 23
6 9 9 25
7 12 4 29
예 2: 새로운 첫 번째 열을 추가하여 순서 변경
다음 코드는 첫 번째 위치에 새 열을 삽입하여 DataFrame의 열 순서를 변경하는 방법을 보여줍니다.
#define new column to add
steals = [2, 3, 3, 4, 3, 2, 1, 2]
#insert new column in first position
df. insert (0, ' steals ', steals)
#display dataFrame
df
steals points assists rebounds
0 2 25 5 11
1 3 12 7 8
2 3 15 7 10
3 4 14 9 6
4 3 19 12 6
5 2 23 9 5
6 1 25 9 9
7 2 29 4 12
예 3: 새로운 마지막 열을 추가하여 순서 변경
다음 코드는 DataFrame의 마지막 위치에 새 열을 삽입하여 DataFrame의 열 순서를 변경하는 방법을 보여줍니다.
#define new column to add
steals = [2, 3, 3, 4, 3, 2, 1, 2]
#insert new column in last position
df. insert ( len ( df.columns ), ' steals ', steals)
#display dataFrame
df
points assists rebounds steals
0 25 5 11 2
1 12 7 8 3
2 15 7 10 3
3 14 9 6 4
4 19 12 6 3
5 23 9 5 2
6 25 9 9 1
7 29 4 12 2
추가 리소스
Pandas DataFrame에 열을 삽입하는 방법
Pandas에서 인덱스 열을 제거하는 방법
Pandas에서 두 열을 결합하는 방법