Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Pandas DataFrame에서 하나 이상의 열 데이터 유형 변경하기 - astype() 메서드 완벽 가이드

이 튜토리얼에서는 Pandas DataFrame에서 하나 이상의 열(column)의 데이터 유형을 다른 유형으로 변환하는 방법을 알아보겠습니다. 이를 위해 DataFrame.astype() 메서드를 사용합니다.

astype() 메서드에는 Python, Pandas, NumPy에서 제공하는 모든 데이터 유형을 인자로 전달할 수 있습니다. 또한 열 이름과 원하는 데이터 유형으로 구성된 딕셔너리(dictionary)를 전달하면 특정 열의 데이터 유형만 선택적으로 변경할 수도 있습니다. 그럼 코드 예제를 통해 자세히 살펴보겠습니다.

예제 1: 모든 열의 데이터 유형을 문자열(str)로 변경

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# we will change the data type of all columns to str
data_frame = data_frame.astype(str)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

위 예제에서는 astype(str)을 호출하여 DataFrame의 모든 열을 문자열(object) 유형으로 변환했습니다. 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

No     object
Name   object
Age    object
dtype: object

출력 결과에서 확인할 수 있듯이 No, Name, Age 세 열 모두 object(문자열) 유형으로 성공적으로 변경되었습니다.

예제 2: 딕셔너리를 사용해 특정 열만 변경

이번에는 Age 열의 데이터 유형만 int에서 str로 변경해 보겠습니다. 이 경우 열 이름을 키(key)로, 원하는 데이터 유형을 값(value)으로 갖는 딕셔너리를 생성한 뒤 astype() 메서드에 전달하면 됩니다.

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# creating a dictionary with column name and data type
data_types_dict = {'Age': str}
# we will change the data type of Age column to str by giving the dict to the astype method
data_frame = data_frame.astype(data_types_dict)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

실행 결과를 보면 Age 열의 데이터 유형만 int64에서 object(str)로 변경된 것을 확인할 수 있습니다. 나머지 열은 원래 유형을 그대로 유지합니다.

No      int64
Name   object
Age    object
dtype: object

마무리

지금까지 Pandas의 astype() 메서드를 활용해 DataFrame 열의 데이터 유형을 변경하는 두 가지 방법을 살펴보았습니다. 데이터 유형을 직접 전달하면 전체 열을 한 번에 변환할 수 있고, 딕셔너리를 사용하면 필요한 열만 선택적으로 변환할 수 있습니다. 실무에서는 데이터 정제 과정에서 숫자형과 문자형 간 변환이 자주 필요하므로 이 두 가지 방식을 모두 익혀두면 큰 도움이 됩니다. 튜토리얼을 따라 하면서 어려운 점이 있다면 댓글로 남겨주세요.