수정 방법: typeerror: –: 'str' 및 'int'에 대해 지원되지 않는 피연산자 유형


Python을 사용할 때 발생할 수 있는 오류는 다음과 같습니다.

 TypeError : unsupported operand type(s) for -: 'str' and 'int'

이 오류는 문자열 변수와 숫자 변수를 사용하여 뺄셈을 수행하려고 할 때 발생합니다.

다음 예에서는 실제로 이 오류를 해결하는 방법을 보여줍니다.

오류를 재현하는 방법

다음과 같은 팬더 DataFrame이 있다고 가정합니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   ' points_for ': ['18', '22', '19', '14', '14', '11', '20', '28'],
                   ' points_against ': [5, 7, 17, 22, 12, 9, 9, 4]})

#view DataFrame
print (df)

  team points_for points_against
0 to 18 5
1 B 22 7
2 C 19 17
3 D 14 22
4 E 14 12
5 F 11 9
6 G 20 9
7:28 a.m. 4

#view data type of each column
print ( df.dtypes )

team object
points_for object
points_against int64
dtype:object

이제 points_for 열에서 points_against 열을 빼려고 한다고 가정합니다.

 #attempt to perform subtraction
df[' diff '] = df. points_for - df. points_against

TypeError : unsupported operand type(s) for -: 'str' and 'int'

points_for 열은 문자열이고 points_against 열은 숫자이기 때문에 TypeError 가 발생합니다.

빼기를 수행하려면 두 열이 모두 숫자여야 합니다.

오류를 수정하는 방법

이 오류를 해결하려면 뺄셈을 수행하기 전에 .astype(int)을 사용하여 points_for 열을 정수로 변환하면 됩니다.

 #convert points_for column to integer
df[' points_for '] = df[' points_for ']. astype (int)

#perform subtraction
df[' diff '] = df. points_for - df. points_against

#view updated DataFrame
print (df)

  team points_for points_against diff
0 A 18 5 13
1 B 22 7 15
2 C 19 17 2
3 D 14 22 -8
4 E 14 12 2
5 F 11 9 2
6 G 20 9 11
7:28 4 24

#view data type of each column
print ( df.dtypes )

team object
points_for int32
points_against int64
diff int64
dtype:object

뺄셈에 사용한 두 열은 숫자 열이므로 오류가 발생하지 않습니다.

추가 리소스

다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.

Pandas에서 KeyError를 수정하는 방법
수정 방법: ValueError: float NaN을 int로 변환할 수 없습니다.
해결 방법: ValueError: 피연산자를 모양과 함께 브로드캐스트할 수 없습니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다