- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经阅读了有关不向数据库添加重复记录的 Pandas to_sql 解决方案。我正在处理日志的 csv 文件,每次我上传一个新的日志文件时,我都会读取数据并使用 Pandas 创建一个新的数据框进行一些更改。
然后我执行 to_sql('Logs',con = db.engine, if_exists = 'append', index=True)
.与 if_exists
arg i
确保每次从新文件中新创建的数据框都附加到现有数据库中。问题是它不断添加重复的值。我想确保如果一个已经上传的文件被错误地再次上传,它不会被附加到数据库中。我想在创建数据库时直接尝试这样做,而没有找到解决方法,例如检查之前是否使用过文件名。
我正在使用flask-sqlalchemy。
谢谢你。
最佳答案
最好的办法是通过将索引设置为主键来捕获重复项,然后使用 try
/except
捕获唯一性违规。你提到了另一篇建议关注 IntegrityError
的帖子。异常(exception),我同意这是最好的方法。您可以将其与去重功能结合使用,以确保您的表更新顺利运行。
演示问题
这是一个玩具示例:
from sqlalchemy import *
import sqlite3
# make a database, 'test', and a table, 'foo'.
conn = sqlite3.connect("test.db")
c = conn.cursor()
# id is a primary key. this will be the index column imported from to_sql().
c.execute('CREATE TABLE foo (id integer PRIMARY KEY, foo integer NOT NULL);')
# use the sqlalchemy engine.
engine = create_engine('sqlite:///test.db')
pd.read_sql("pragma table_info(foo)", con=engine)
cid name type notnull dflt_value pk
0 0 id integer 0 None 1
1 1 foo integer 1 None 0
df
和
df2
:
data = {'foo':[1,2,3]}
df = pd.DataFrame(data)
df
foo
0 1
1 2
2 3
data2 = {'foo':[3,4,5]}
df2 = pd.DataFrame(data2, index=[2,3,4])
df2
foo
2 3 # this row is a duplicate of df.iloc[2,:]
3 4
4 5
df
进表
foo
:
df.to_sql('foo', con=engine, index=True, index_label='id', if_exists='append')
pd.read_sql('foo', con=engine)
id foo
0 0 1
1 1 2
2 2 3
df2
,我们 catch 了
IntegrityError
:
try:
df2.to_sql('foo', con=engine, index=True, index_label='id', if_exists='append')
# use the generic Exception, both IntegrityError and sqlite3.IntegrityError caused trouble.
except Exception as e:
print("FAILURE TO APPEND: {}".format(e))
FAILURE TO APPEND: (sqlite3.IntegrityError) UNIQUE constraint failed: foo.id [SQL: 'INSERT INTO foo (id, foo) VALUES (?, ?)'] [parameters: ((2, 3), (3, 4), (4, 5))]
IntegrityError
,您可以拉取现有表数据,删除新数据的重复条目,然后重试 append 语句。使用
apply()
为了这:
def append_db(data):
try:
data.to_sql('foo', con=engine, index=True, index_label='id', if_exists='append')
return 'Success'
except Exception as e:
print("Initial failure to append: {}\n".format(e))
print("Attempting to rectify...")
existing = pd.read_sql('foo', con=engine)
to_insert = data.reset_index().rename(columns={'index':'id'})
mask = ~to_insert.id.isin(existing.id)
try:
to_insert.loc[mask].to_sql('foo', con=engine, index=False, if_exists='append')
print("Successful deduplication.")
except Exception as e2:
"Could not rectify duplicate entries. \n{}".format(e2)
return 'Success after dedupe'
df2.apply(append_db)
Initial failure to append: (sqlite3.IntegrityError) UNIQUE constraint failed: foo.id [SQL: 'INSERT INTO foo (id, foo) VALUES (?, ?)'] [parameters: ((2, 3), (3, 4), (4, 5))]
Attempting to rectify...
Successful deduplication.
foo Success after dedupe
dtype: object
关于Pandas to_sql 使索引唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016799/
我已经阅读了有关不向数据库添加重复记录的 Pandas to_sql 解决方案。我正在处理日志的 csv 文件,每次我上传一个新的日志文件时,我都会读取数据并使用 Pandas 创建一个新的数据框进行
我正在将PANDAS与SQLAlchemy一起使用DataFrame.to_sql写入MYSQL DB。我喜欢打开'append' --> df.to_sql(con=con, name='table
我有一个看起来像这样的数据框 id_1 id_2 id_3 ... date_1 1 3 4 date_2 4
我想将数据帧写入现有的 sqlite(或 mysql)表,有时数据帧将包含数据库中尚不存在的新列。我需要做什么才能避免抛出错误?有没有办法告诉 pandas 或 sqlalchemy 使用潜在的新列自
我正在尝试使用Django的db连接变量将pandas数据帧插入Postgres数据库。我使用的代码是 df.to_sql('forecast',connection,if_exists='appen
我目前正在尝试稍微调整一些脚本的性能,似乎瓶颈始终是使用 pandas to_sql 函数实际插入数据库(=MSSQL)。 造成这种情况的一个因素是 mssql 的参数限制为 2100。 我与 sql
有人经历过这种情况吗? 我有一个包含“int”和“varchar”列的表 - 一个报告时间表。 我正在尝试使用 python 程序将扩展名为“.xls”的 Excel 文件导入到该表中。我正在使用 p
我正在尝试将 pandas 数据框保存为 SQL 文件 我按照文档进行了尝试 from sqlalchemy import create_engine engine = create_engine('
Panda 的 to_sql() 和 if_exists='replace' 为我的表设置了错误的字符集。为了将多个 csv 复制到 mysql 并忽略行上的错误(如重复错误),我首先将 csv 读取
我有一个如下所示的数据框: df = pd.DataFrame(index= pd.date_range('2014-01-01', periods=10)) df['date'] = df.inde
我正在尝试使用 Pandas to_sql 将 .csv 文件中的数据插入到 mssql 数据库中。不管我怎么看,我都会遇到这个错误: pyodbc.DataError: ('String data,
我想不断将数据帧行添加到 MySQL 数据库中,避免任何重复的条目进入 MySQL。 我目前通过使用 df.apply() 遍历每一行并调用 MySQL insert ignore(duplicate
如何使用 df.to_sql(if_exists = 'append') 仅附加数据框和数据库之间的唯一值。换句话说,我想评估 DF 和 DB 之间的重复项,并在写入数据库之前删除这些重复项。 这个有
我有一个订购的 Pandas Dataframe。 a0 b0 c0 d0 370025442 370020440 370020436
我正在尝试使用 Python 的 pandas to_sql 命令将月度数据发送到 MySQL 数据库。我的程序一次运行一个月的数据,我想将新数据附加到现有数据库中。然而,Python 给我一个错误:
我正在使用 df.to_sql(con=con_mysql, name='testdata', if_exists='replace', flavor='mysql') 将数据框导出到 mysql。但
我有一个 1,000,000 x 50 Pandas DataFrame,我目前正在使用以下方法写入 SQL 表: df.to_sql('my_table', con, index=False) 这需
我有一个字符串格式的数字列,我想将它作为 float 发送到 PostresSQL。如何确保 SQLAlchemy 将此列设置为 float ? (请注意,列中可能是 NaN)。这是代码 import
我想在我创建的表格中插入一些数据。我有一个如下所示的数据框: 我创建了一个表: create table online.ds_attribution_probabilities ( attributi
我正在使用 Pandas 0.18.1,在摆弄这段代码时, import pd def getIndividualDf(item): var1 = [] # ... populate
我是一名优秀的程序员,十分优秀!