Pandas代码报错TypeError:仅能拼接字符串,无法拼接字符串与整数
问题排查与解决
错误原因
你遇到的TypeError本质是字符串与整数的非法拼接,触发点在代码中的df_rates['Mins before time'] + lookback_minutes部分,核心诱因有两种:
- 列数据类型错误:
df_rates['Mins before time']列的存储类型是字符串而非数值(int/float),和整数lookback_minutes相加时被当成字符串拼接操作,直接触发类型错误。 - 索引与列混淆:根据你描述的
df_rates结构,"Mins before time"是索引的名称而非列名,你错误地用列访问方式df_rates['Mins before time']获取数据,实际返回的是索引名的字符串,而非分钟数值。
另外还有一个潜在问题:如果df_rates的列名是字符串格式的时间(而非Timestamp),直接用df_rates.columns[-1]获取的anchor_time会是字符串类型,后续和时间差运算也会引发异常。
修正后的代码
情况1:"Mins before time"是索引名称
import pandas as pd # 确保anchor_time是Timestamp类型(兼容列名为字符串的情况) anchor_time = pd.to_datetime(df_rates.columns[-1]) lookback_minutes = 30 # 获取索引中的分钟数并转为数值类型,计算总偏移时长 total_minutes = df_rates.index.astype(int) + lookback_minutes # 重新设置索引并关联df_profit df_rates = (df_rates .set_index(anchor_time - pd.to_timedelta(total_minutes, unit='min')) .join(df_profit) .reset_index(drop=True))
情况2:"Mins before time"确实是列名
import pandas as pd anchor_time = pd.to_datetime(df_rates.columns[-1]) lookback_minutes = 30 # 先将列转为整数类型,避免字符串拼接错误 df_rates['Mins before time'] = df_rates['Mins before time'].astype(int) total_minutes = df_rates['Mins before time'] + lookback_minutes df_rates = (df_rates .set_index(anchor_time - pd.to_timedelta(total_minutes, unit='min')) .join(df_profit) .reset_index(drop=True))
验证步骤
- 执行
print(df_rates.info())确认"Mins before time"是索引还是列,以及对应的数据类型。 - 执行
print(type(anchor_time)),确保其类型为pandas._libs.tslibs.timestamps.Timestamp而非字符串。
内容的提问来源于stack exchange,提问作者A Newbie
相关产品推荐
相关产品推荐

