수정 방법: 문자열 값에는 .str 접근자만 사용할 수 있습니다.
Python을 사용할 때 발생할 수 있는 오류는 다음과 같습니다.
AttributeError : Can only use .str accessor with string values!
이 오류는 일반적으로 Pandas DataFrame의 문자열 열에서 패턴을 바꾸려고 할 때 발생하지만 작업 중인 열은 실제로 문자열이 아닙니다.
다음 예에서는 실제로 이 오류를 수정하는 방법을 보여줍니다.
오류를 재현하는 방법
다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
' points ': [6.5, 7.8, 8.0, 9.0, 7.5, 3.4, 6.6, 6.8],
' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
team points assists rebounds
0 A 6.5 5 11
1 A 7.8 7 8
2 A 8.0 7 10
3 A 9.0 9 6
4 B 7.5 12 6
5 B 3.4 9 5
6 B 6.6 9 9
7 B 6.8 4 12
이제 “points” 열의 각 소수점 자리를 공백으로 바꾸려고 한다고 가정합니다.
#attempt to replace decimal in "points" column with a blank
df[' points '] = df[' points ']. str . replace (' . ', '')
AttributeError : Can only use .str accessor with string values!
“포인트” 열이 문자열 열이 아니기 때문에 오류가 발생합니다.
오류를 수정하는 방법
이 오류를 해결하는 가장 쉬운 방법은 “포인트” 열의 값을 바꾸기 전에 .astype(str) 함수를 사용하는 것입니다.
#replace decimal in "points" column with a blank
df[' points '] = df[' points ']. astype (str). str . replace (' . ', '')
#view updated DataFrame
df
team points assists rebounds
0 A 65 5 11
1 A 78 7 8
2 A 80 7 10
3 A 90 9 6
4 B 75 12 6
5 B 34 9 5
6 B 66 9 9
7 B 68 4 12
“points” 열의 모든 소수점 자리가 바뀌었고 “points” 열의 값을 바꾸려고 하기 전에 .astype(str) 함수를 사용했기 때문에 오류가 발생하지 않습니다.
참고 : 여기에서 replacement() 함수에 대한 전체 문서를 찾을 수 있습니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
Pandas에서 KeyError를 수정하는 방법
수정 방법: ValueError: float NaN을 int로 변환할 수 없습니다.
해결 방법: ValueError: 피연산자를 모양과 함께 브로드캐스트할 수 없습니다.