首页 > 解决方案 > 如何将熊猫系列作为一行存储到sql

问题描述

我有一个 pandasDataframe对象,我遍历行:

for idx, row in df.iterrows():
    # do some stuff
    # save row to database

问题是当我尝试将其保存到数据库时,to_sql将 myrow作为column

该变量row似乎是 type Series,我仔细搜索Series.to_sql了手册中的 ,我没有看到任何将其视为数据库row而不是column的方法。

我想出的解决方法是将 a 转换Series为 aDataFrame然后转置它:

    temp = pd.DataFrame(row).T
    temp.to_sql(table, con=engine, if_exists='append', index_label='idx')

有没有更简单的方法?

标签: pythonpython-3.xpandasseries

解决方案


与使用df.iterrows返回索引和每行的序列表示的 use 不同,一种方法是迭代df.index并使用基于整数位置的索引来切片数据帧以进行行操作。

df = pd.DataFrame.from_dict({'a':[1,2,3],'b':[4,5,6]})
for i in range(df.index):
    row = df.iloc[i:i+1,:]
    #do Stuff
    row.to_sql(...)

这是修改数据框的推荐方法。从df.iterrows文档字符串:

2. You should **never modify** something you are iterating over.
   This is not guaranteed to work in all cases. Depending on the
   data types, the iterator returns a copy and not a view, and writing
   to it will have no effect.

推荐阅读