Pandas dataframe에서 인덱스로 열을 선택하는 방법
종종 인덱스 값을 기반으로 pandas DataFrame에서 열을 선택하려는 경우가 있습니다.
정수 인덱싱을 기반으로 열을 선택하려면 .iloc 함수를 사용할 수 있습니다.
레이블 인덱싱을 기반으로 열을 선택하려면 .loc 함수를 사용할 수 있습니다.
이 튜토리얼에서는 이러한 각 기능을 실제로 사용하는 방법에 대한 예를 제공합니다.
예 1: 정수 인덱싱을 기반으로 열 선택
다음 코드는 pandas DataFrame을 생성하고 .iloc를 사용하여 정수 인덱스 값이 3 인 열을 선택하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B'], ' points ': [11, 7, 8, 10, 13, 13], ' assists ': [5, 7, 7, 9, 12, 9], ' rebounds ': [11, 8, 10, 6, 6, 5]}) #view DataFrame df team points assists rebounds 0 A 11 5 11 1 To 7 7 8 2 to 8 7 10 3 B 10 9 6 4 B 13 12 6 5 B 13 9 5 #select column with index position 3 df. iloc [:, 3] 0 11 1 8 2 10 3 6 4 6 5 5 Name: rebounds, dtype: int64
비슷한 구문을 사용하여 여러 열을 선택할 수 있습니다.
#select columns with index positions 1 and 3
df. iloc [:, [1, 3]]
rebound points
0 11 11
1 7 8
2 8 10
3 10 6
4 13 6
5 13 5
또는 범위의 모든 열을 선택할 수도 있습니다.
#select columns with index positions in range 0 through 3
df. iloc [:, 0:3]
team points assists
0 to 11 5
1 To 7 7
2 to 8 7
3 B 10 9
4 B 13 12
5 B 13 9
예 2: 레이블 인덱싱을 기반으로 열 선택
다음 코드는 pandas DataFrame을 생성하고 .loc를 사용하여 인덱스 레이블이 “bounces” 인 열을 선택하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B'], ' points ': [11, 7, 8, 10, 13, 13], ' assists ': [5, 7, 7, 9, 12, 9], ' rebounds ': [11, 8, 10, 6, 6, 5]}) #view DataFrame df team points assists rebounds 0 A 11 5 11 1 To 7 7 8 2 to 8 7 10 3 B 10 9 6 4 B 13 12 6 5 B 13 9 5 #select column with index label 'rebounds' df. loc [:, ' rebounds '] 0 11 1 8 2 10 3 6 4 6 5 5 Name: rebounds, dtype: int64
비슷한 구문을 사용하여 인덱스 레이블이 다른 여러 열을 선택할 수 있습니다.
#select the columns with index labels 'points' and 'rebounds'
df. loc [:,[' points ',' rebounds ']]
rebound points
0 11 11
1 7 8
2 8 10
3 10 6
4 13 6
5 13 5
또는 범위의 모든 열을 선택할 수도 있습니다.
#select columns with index labels between 'team' and 'assists'
df. loc [:, ' team ':' assists ']
team points assists
0 to 11 5
1 To 7 7
2 to 8 7
3 B 10 9
4 B 13 12
5 B 13 9
관련 항목:Pandas loc vs iloc: 차이점은 무엇인가요?
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas DataFrame에서 인덱스별로 그룹화하는 방법
Pandas DataFrame에서 인덱스로 행을 선택하는 방법
Pandas DataFrame에서 행 번호를 얻는 방법
Pandas DataFrame에서 인덱스 열을 제거하는 방법