Python Pandas의 열 이름에서 열 인덱스를 가져오려면 get_loc()을 사용할 수 있습니다. 방법.
단계 -
- 크기가 변경 가능한 2차원 테이블 형식 데이터 df 생성 .
- 입력 DataFrame, df 인쇄 .
- df.columns를 사용하여 DataFrame의 열 찾기 .
- 3단계의 열을 인쇄합니다.
- 변수 column_name 초기화 .
- column_name에 대한 색인의 위치를 가져옵니다. .
- column_name의 색인 인쇄 .
예시 -
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print"Input DataFrame 1 is:\n", df
columns = df.columns
print"Columns in the given DataFrame: ", columns
column_name = "z"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index
column_name = "x"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index
column_name = "y"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index 출력
Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Columns in the given DataFrame: Index(['x', 'y', 'z'], dtype='object') Index of the column z is: 2 Index of the column x is: 0 Index of the column y is: 1