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

如何将含行标识的Pandas DataFrame正确写入数据库?

解决方法

1. 恢复行标识为可查询列

核心是将自定义行索引转为数据库能识别的显式列(比如命名为row),分两种场景处理:

场景1:仍能访问原始df1

直接把行索引转为普通列:

# 将df1的索引转为名为'row'的列,同时移除原索引
df_processed = df1.reset_index(names='row')

处理后df_processed会新增row列,值为server、cpu、mixer,原有列parent_child1至parent_child5保留。

场景2:仅能访问丢失索引的df2

如果df2的行顺序和原df1完全一致(第0行对应server,第1行对应cpu,第2行对应mixer),手动添加行标识列:

# 按顺序定义原始行标识
row_labels = ['server', 'cpu', 'mixer']
# 新增row列并调整列顺序(可选,让row列排在最前)
df_processed = df2.assign(row=row_labels)
df_processed = df_processed[['row'] + [col for col in df2.columns if col != 'row']]

2. 写入数据库

使用pandas.to_sql方法写入,注意关闭默认索引写入:

from sqlalchemy import create_engine

# 以MySQL为例,替换为你的数据库连接信息
engine = create_engine('mysql+pymysql://用户名:密码@主机地址:端口/数据库名')

# 写入表tble_db,if_exists可根据需求选replace/append/fail
df_processed.to_sql(name='tble_db', con=engine, if_exists='replace', index=False)

设置index=False是因为我们已经把自定义索引转成了row列,无需再写入默认的数字索引。

3. 执行查询验证

现在可以直接运行目标SQL语句:

SELECT parent_child1 FROM tble_db WHERE row='server';

预防索引丢失的小技巧

如果是从嵌套字典生成DataFrame时容易丢失索引,直接用from_dict并指定orient='index':

import pandas as pd

# 假设nested_dict是你的原始嵌套字典
nested_dict = {
    'server': {'parent_child1': 10, 'parent_child2': 20},
    'cpu': {'parent_child1': 30, 'parent_child2': 40},
    'mixer': {'parent_child1': 50, 'parent_child2': 60}
}
# 直接将字典键作为行索引生成DataFrame
df1 = pd.DataFrame.from_dict(nested_dict, orient='index')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:35:22