아미(아름다운미소)

컬럼명을 닥셔너리에 저장 후 불러쓰기 본문

랭귀지/python

컬럼명을 닥셔너리에 저장 후 불러쓰기

유키공 2024. 7. 1. 14:53

1)

import pandas as pd

# 타입을 지정한 딕셔너리 생성
col_dict = {
    'first_col': 'str',
    'second_col': 'int',
    'third_col': 'float'
}

# 데이터프레임 생성
df = pd.DataFrame({
    'first_col': ['a', 'b', 'c'],
    'second_col': [1, 2, 3],
    'third_col': [1.1, 2.2, 3.3]
})

# 컬럼 타입 지정
for col, dtype in col_dict.items():
    df[col] = df[col].astype(dtype)

# 컬럼명 출력
print(list(col_dict.keys())[2])

2)

import pandas as pd

# 데이터프레임 생성
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# 컬럼명을 딕셔너리에 저장
col_dict = {
    'first_col': 'A',
    'second_col': 'B',
    'third_col': 'C'
}

# 딕셔너리의 키를 이용하여 컬럼 선택
print(df[col_dict['first_col']])
print(df[col_dict['second_col']])
print(df[col_dict['third_col']])
Comments