首页 > 解决方案 > 熊猫读取和大型数据库并在之后将其写回

问题描述

我正在尝试使用 pandas 和 SQL 读取一个大的 .db 文件,但它使用了大量的 ram 并且需要很长时间才能完成。

.db 文件有超过 500 万行。

我怎样才能做同样的事情,但用更少的内存和更快的方式?

import pandas as pd
import sqlite3, shutil, glob, os
from pathlib import Path

#create folder if doesn't exist
NewFolderPath  = r"C:\Databases\\"
isFile = os.path.exists(NewFolderPath)
if isFile is False:
    Path(NewFolderPath).mkdir(parents=True, exist_ok=True)

df = pd.DataFrame()

#SQL Connect
conn = sqlite3.connect(NewFolderPath+'hist_prices.db')
c = conn.cursor()
#dest = sqlite3.connect(':memory:')
#conn.backup(dest)
conn.commit()

df = pd.read_sql_query("SELECT * from hist_prices", conn)
df.drop_duplicates(subset=None, keep="last", inplace=True)
df.to_sql('hist_prices', conn,  if_exists='replace', index=False)

标签: pythonpandas

解决方案


推荐阅读