如何将pandas系列作为一行存储到sql中

问题描述 投票:0回答:1

我有一个pandas Dataframe对象,我迭代遍历行:

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

问题是当我尝试将其保存到数据库时,to_sql将我的row视为一列。

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

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

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

有更简单的方法吗?

python python-3.x pandas series
1个回答
0
投票

而不是使用返回索引和每行的一系列表示的df.iterrows,一种方法是迭代df.index并使用integer-location based indexing切片数据帧以进行行操作。

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 docstring:

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.
© www.soinside.com 2019 - 2024. All rights reserved.