我有一个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')
有更简单的方法吗?
而不是使用返回索引和每行的一系列表示的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.