如何解决pandas to_sql写入SQLite时的duplicate column name: timestamp错误?
解决SQLite保存DataFrame时的"duplicate column name: timestamp"错误
问题原因
你的DataFrame同时存在名为timestamp的列和同名的索引,当pandas的to_sql方法默认将索引也作为一列写入数据库时,就会触发列名重复的错误。从处理后的DataFrame结构可以明确看到:
- 行索引是
timestamp类型的时间戳 - 数据列中也保留了
timestamp字段
解决方案
方法1:删除重复的timestamp列,保留索引
既然已经将时间戳设为索引,原timestamp列属于冗余数据,直接删除后再保存:
# 删除原timestamp列 new_df = new_df.drop(columns=['timestamp']) # 保存时将索引作为timestamp列写入数据库 new_df.to_sql( "ohlc_minutes_filtered", conn, if_exists='replace', index=True, index_label='timestamp' # 指定索引列的名称为timestamp )
方法2:不写入索引,保留原timestamp列
如果需要保留原timestamp列,保存时禁止将索引写入数据库:
new_df.to_sql("ohlc_minutes_filtered", conn, if_exists='replace', index=False)
方法3:优化处理流程,提前避免重复
在分组数据处理阶段,设置索引时直接删除原timestamp列,从根源避免重复:
for name, ohlc in seperate_days: # 设置索引并删除原timestamp列 ohlc = ohlc.set_index('timestamp', drop=True) # 计算累计成交量 ohlc['cum_volume'] = ohlc["volume"].cumsum() # 判断累计成交量是否超过25k ohlc['cum_volume_is_>_25k'] = np.where(ohlc['cum_volume'] > 25000, True, False) # 先获取盘前时间索引,再更新标记(原代码顺序错误,会导致变量未定义) open_hours_indices = ohlc.index.indexer_between_time('04:00', '09:29') open_hours_index = ohlc.index[open_hours_indices] ohlc['cum_volume_is_>_25k'][~ohlc.index.isin(open_hours_index)] = False new_df = new_df.append(ohlc)
注:原代码中存在逻辑顺序错误——先修改
cum_volume_is_>_25k再定义open_hours_index,会触发未定义变量的报错,上述代码已修正该问题。
内容的提问来源于stack exchange,提问作者a7dc
相关产品推荐
相关产品推荐

