简体   繁体   中英

How do I fix TypeError in Python

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM