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

파이썬으로 데이터프레임에서 특정 열의 데이터 유형 변환하기

데이터프레임이 있고, float 타입의 열을 int 타입으로 변환하면 결과가 다음과 같이 나타난다고 가정해 보겠습니다.

변환 전
Name      object
Age       int64
Maths     int64
Science   int64
English   int64
Result    float64
dtype: object

변환 후

Name      object
Age       int64
Maths     int64
Science   int64
English   int64
Result    int64
dtype: object

이 문제를 해결하기 위해 아래 단계를 따릅니다.

해결 방법

  • 먼저 데이터프레임을 정의합니다.

  • float 타입인 'Result' 열을 astype() 메서드를 사용하여 다음과 같이 'int' 타입으로 변환합니다.

df.Result.astype(int)

astype()은 판다스에서 제공하는 데이터 유형 변환 메서드로, 원하는 dtype을 인자로 전달하면 해당 열의 데이터 유형을 일괄 변경할 수 있습니다.

예제

아래 구현 예제를 통해 더 자세히 이해해 보겠습니다.

import pandas as pd
data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
        'Age' : [13,12,12,13,12],
        'Maths': [98, 59, 66, 95, 70],
        'Science': [75, 96, 55, 49, 78],
        'English': [79, 45, 70, 60, 80],
        'Result': [8.1,6.2,6.3,7.2,8.3]}
df = pd.DataFrame(data)
print("Before conversion\n", df.dtypes)
df.Result = df.Result.astype(int)
print("After conversion\n",df.dtypes)

출력 결과

Name      object
Age       int64
Maths     int64
Science   int64
English   int64
Result    float64
dtype: object
Name      object
Age       int64
Maths     int64
Science   int64
English   int64
Result    int64
dtype: object

출력 결과를 보면 변환 전에는 'Result' 열이 float64 타입이었지만, astype(int)를 적용한 후에는 int64 타입으로 성공적으로 변경된 것을 확인할 수 있습니다. 참고로 astype(int)는 소수점 이하 값을 버리므로, 반올림이 필요한 경우 round() 메서드를 먼저 적용하는 것이 좋습니다.