python - 如何将熊猫系列作为一行存储到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')
有没有更简单的方法?
解决方案
与使用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.
推荐阅读
- spring-boot - 使用 JHipster-Registry(Cloud Config Server 作为中央服务器)集中微服务时 Bean-Definition Overriding Exception
- c - 局部变量帮帮我
- javascript - 在未动态修改的页面中使用 MutationObserver
- azure-ad-b2c - 具有默认值的 ContentDefinitionParameters
- android - android studio动画结束后继续程序
- amazon-web-services - 如何定期从 Lambda 发送失败消息
- java - Java 中的容器 (AWT) 对象
- reactjs - 反应渲染两次!!!我怎样才能停止重新渲染?
- elasticsearch - ELASTICSEARCH - 过滤重复结果
- react-native - 有没有办法使用 react-native 显示“下载完成”通知?