Pandas dataframe에서 부울을 문자열로 변환하는 방법
다음 기본 구문을 사용하여 부울 열을 Pandas DataFrame의 문자열 열로 변환할 수 있습니다.
df[' my_bool_column '] = df[' my_bool_column ']. replace ({ True : ' True ', False : ' False '})
이 특정 예에서는 my_bool_column 이라는 열에서 각 True 값을 “True” 문자열로 바꾸고 각 False 값을 “False” 문자열로 바꿉니다.
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Pandas에서 부울을 문자열로 변환
다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G'], ' points ': [18,20, 25, 40, 34, 32, 19], ' all_star ': [True, False, True, True, True, False, False], ' starter ': [False, True, True, True, False, False, False]}) #view DataFrame print (df) team points all_star starter 0 A 18 True False 1 B 20 False True 2 C 25 True True 3 D 40 True True 4 E 34 True False 5 F 32 False False 6 G 19 False False
dtypes 함수를 사용하여 DataFrame의 각 열의 데이터 유형을 확인할 수 있습니다.
#view data type of each column print ( df.dtypes ) team object int64 dots all_star bool starter bool dtype:object
결과에서 all_star 및 starter 열이 모두 부울임을 알 수 있습니다.
다음 구문을 사용하여 all_star 열을 문자열 열로 변환할 수 있습니다.
#convert Boolean values in all_star column to strings
df[' all_star '] = df[' all_star ']. replace ({ True : ' True ', False : ' False '})
#view updated DataFrame
print (df)
team points all_star starter
0 A 18 True False
1 B 20 False True
2 C 25 True True
3 D 40 True True
4 E 34 True False
5 F 32 False False
6 G 19 False False
#view updated data types of each column
print ( df.dtypes )
team object
int64 dots
all_star object
starter bool
dtype:object
결과에서 all_star 열이 문자열 열로 변환된 것을 확인할 수 있습니다.
all_star 및 시작 열을 부울에서 문자열로 변환하려면 다음 구문을 사용할 수 있습니다.
#convert Boolean values in all_star and starter columns to strings
df[[' all_star ', ' starter ']] = df[[' all_star ', ' starter ']]. replace ({ True : ' True ', False : ' False '})
#view updated DataFrame
print (df)
team points all_star starter
0 A 18 True False
1 B 20 False True
2 C 25 True True
3 D 40 True True
4 E 34 True False
5 F 32 False False
6 G 19 False False
#view updated data types of each column
print ( df.dtypes )
team object
int64 dots
all_star object
starter object
dtype:object
결과에서 두 부울 열이 모두 문자열로 변환되었음을 확인할 수 있습니다.
참고: pandas replacement() 함수에 대한 전체 문서는 여기에서 찾을 수 있습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas: 부울 계열을 사용하여 DataFrame에서 행 선택
Pandas: 조건에 따라 부울 열을 만드는 방법
Pandas: 부울 값을 정수 값으로 변환하는 방법