gpt4 book ai didi

python - 使用 SQL Alchemy 导入数据并替换给定条件

转载 作者:行者123 更新时间:2023-11-29 05:54:30 25 4
gpt4 key购买 nike

下面是我的 selenium 网络抓取工具的最后一部分,循环遍历此 website page 的不同选项卡。 ,选择“导出数据”按钮,下载数据,添加“yearid”列,然后将数据加载到 MySQL 表中。

    df = pd.read_csv(desired_filepath)
df["yearid"] = datetime.today().year
df[df.columns[df.columns.str.contains('%')]] = \
(df.filter(regex='%')
.apply(lambda x: pd.to_numeric(x.str.replace(r'[\s%]', ''),
errors='coerce')))
df.to_csv(desired_filepath)

engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="walker",
pw="password",
db="data"))
df.to_sql(con=engine, name='fg_test_hitting_{}'.format(button_text), if_exists='replace')

time.sleep(10)
driver.quit()

一切正常,但我想将数据导入 MySQL 表并仅在 yearid=2018 时替换。有谁知道在给定特定条件下是否可以加载数据和替换数据?提前致谢!

最佳答案

我认为与其从您的表中删除,不如让 MySQL 处理替换可能更好。您可以通过使用新数据创建临时表,替换为永久表,然后删除临时表来完成此操作。这里最大的警告是您需要在表中设置键(最好只设置一次)。我不知道你的关键领域是什么,所以很难在这方面提供帮助。

将注释行替换为:

# df.to_sql(con=engine, name='fg_test_hitting_{}'.format(button_text), if_exists='replace')
conn = engine.connect()

# should fail if temporary table already exists (we want it to fail in this case)
df.to_sql('fg_test_hitting_{}_tmp'.format(button_text), conn)

# Will create the permanent table if it does not already exist (will only matter in the first run)
# note that you may have to create keys here so that mysql knows what constitutes a replacement
conn.execute('CREATE TABLE IF NOT EXISTS fg_test_hitting_{} LIKE fg_test_hitting_{}_tmp;'.format(button_text, button_text))

# updating the permanent table and dropping the temporary table
conn.execute('REPLACE INTO fg_test_hitting_{} (SELECT * FROM fg_test_hitting_{}_tmp);'.format(button_text, button_text))
conn.execute('DROP TABLE IF EXISTS fg_test_hitting_{}_tmp;'.format(button_text))

关于python - 使用 SQL Alchemy 导入数据并替换给定条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50938216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com