Pandas에서 문자열을 부동 소수점으로 변환하는 방법
다음 방법을 사용하여 팬더에서 문자열을 부동 소수점으로 변환할 수 있습니다.
방법 1: 단일 열을 부동 열로 변환
#convert "assists" column from string to float df[' assists '] = df[' assists ']. astype (float)
방법 2: 여러 열을 부동 열로 변환
#convert both "assists" and "rebounds" from strings to floats df[[' assists ', ' rebounds ']] = df[[' assists ', ' rebounds ']]. astype (float)
방법 3: 모든 열을 부동 열로 변환
#convert all columns to float df = df. astype (float)
다음 예에서는 다음 pandas DataFrame에서 실제로 각 메서드를 사용하는 방법을 보여줍니다.
import numpy as np import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [np.nan, 12, 15, 14, 19], ' assists ': ['5', np.nan, '7', '9', '12'], ' rebounds ': ['11', '8', '10', '6', '6']}) #view DataFrame df points assists rebounds 0 NaN 5.0 11 1 12.0 NaN 8 2 15.0 7.0 10 3 14.0 9.0 6 4 19.0 12.0 6 #view column data types df. dtypes float64 points assists object rebound object dtype:object
예 1: 단일 열을 부동 열로 변환
다음 구문은 도우미 열을 문자열에서 부동 소수점으로 변환하는 방법을 보여줍니다.
#convert "assists" from string to float df[' assists '] = df[' assists ']. astype (float) #view column data types df. dtypes float64 points assist float64 rebound object dtype:object
예 2: 여러 열을 부동 소수점으로 변환
다음 구문은 도우미 및 바운스 열을 문자열에서 부동 소수점으로 변환하는 방법을 보여줍니다.
#convert both "assists" and "rebounds" from strings to floats df[[' assists ', ' rebounds ']] = df[[' assists ', ' rebounds ']]. astype (float) #view column data types df. dtypes float64 points assist float64 rebounds float64 dtype:object
예시 3: 모든 열을 부동 소수점으로 변환
다음 구문은 DataFrame의 모든 열을 부동 소수점으로 변환하는 방법을 보여줍니다.
#convert all columns to float df = df. astype (float) #view column data types df. dtypes float64 points assist float64 rebounds float64 dtype:object
보너스: 문자열을 부동 소수점으로 변환하고 NaN 값을 채웁니다.
다음 구문은 도우미 열을 문자열에서 부동 소수점으로 변환하는 동시에 NaN 값을 0으로 채우는 방법을 보여줍니다.
#convert "assists" from string to float and fill in NaN values with zeros df[' assists '] = df[' assists ']. astype (float). fillna (0) #view DataFrame df points assists rebounds 0 NaN 5.0 11 1 12.0 0.0 8 2 15.0 7.0 10 3 14.0 9.0 6 4 19.0 12.0 6
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas: 객체를 정수로 변환하는 방법
Pandas: 부동 소수점을 정수로 변환하는 방법
Pandas: 특정 열을 NumPy 배열로 변환하는 방법