Home > database >  How do I fix TypeError in Python
How do I fix TypeError in Python

Time:01-28

It shows the following error

TypeError: can only concatenate str (not "int") to str

Here is the code

data.loc[(data['Account'] == Value) & (data['Contract End Month'] >= 7),
             'End Fiscal Year'] = data['Contract End Year']   1

CodePudding user response:

Looks like your data['Contract End Year'] is an str instance, try casting it into an int before performing the addition:

data.loc[(data['Account'] == Value) & (data['Contract End Month'] >= 7),'End Fiscal Year'] = int(data['Contract End Year'])   1

CodePudding user response:

The error message is indicating that you are trying to concatenate a string with an integer. It seems like the column 'Contract End Year' is of type string, but you're trying to add 1 to it as if it were an integer. You can convert it to int using pandas.to_numeric method and then adding 1, and later you can convert it back to str

data['Contract End Year'] = pd.to_numeric(data['Contract End Year'], errors='coerce')
data.loc[(data['Account'] == Value) & (data['Contract End Month'] >= 7),
             'End Fiscal Year'] = data['Contract End Year']   1
data['End Fiscal Year'] = data['End Fiscal Year'].astype(str)

This should fix the TypeError and allow you to perform the arithmetic operation on the 'Contract End Year' column.

  • Related