You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python中的TypeError:只能拼接str与str,不能拼接int与str

解决TypeError: can only concatenate str (not "int") to str问题

错误原因

data['Contract End Year']列的数据类型是字符串(str),你试图将它与整数1进行运算,而Python不允许字符串和整数直接拼接/相加,因此触发该TypeError。

修复方案

方案1:临时转换列类型后运算(不修改原列)

直接在赋值时将Contract End Year转为整数类型再执行加1操作:

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

方案2:先转换原列类型(适合后续多次使用该列数值运算)

如果后续还需要对Contract End Year进行数值运算,先统一转换列类型:

# 转换原列为整数类型
data['Contract End Year'] = data['Contract End Year'].astype(int)
# 执行赋值
data.loc[(data['Account'] == Value) & (data['Contract End Month'] >= 7),
         'End Fiscal Year'] = data['Contract End Year'] + 1

方案3:若需结果为字符串类型

如果End Fiscal Year需要存储为字符串,可在运算后再转回字符串:

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

注意:如果Contract End Year列存在非数字字符串(比如空值、字母),astype(int)会报错,此时可先用pd.to_numeric处理并转换无效值:

data['Contract End Year'] = pd.to_numeric(data['Contract End Year'], errors='coerce')

其中errors='coerce'会将无效值转为NaN,后续可根据需求处理这些NaN。

内容的提问来源于stack exchange,提问作者sdg30

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:27:52