在sqlite/pandas中复制表和重命名列的精简内存方式

2024-07-04 05:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了一个很好的方法:

  1. 从sql数据库读取表
  2. 使用dict重命名列(从yaml文件读取)
  3. 将表重写到另一个数据库

唯一的问题是,当表变得更大(10col x几百万行)时,将表读入一个内存非常密集的表中会导致进程被终止

一定有更简单的办法。我查看了alter table语句,但它们似乎也非常复杂&;不会在另一个数据库中进行复制。关于如何在不占用这么多内存的情况下执行相同操作的任何想法。因为我的sql不好,我觉得熊猫是我的拐杖

import pandas as pd
import sqlite3
def translate2generic(sourcedb, targetdb, sourcetable,
                      targettable, toberenamed):
    """Change table's column names to fit generic api keys.

    :param: Path to source db
    :param: Path to target db
    :param: Name of table to be translated in source
    :param: Name of the newly to be created table in targetdb
    :param: dictionary of translations
    :return: New column names in target db
    """
    sourceconn = sqlite3.connect(sourcedb)
    targetconn = sqlite3.connect(targetdb)
    table = pd.read_sql_query('select * from ' + sourcetable, sourceconn) #this is the line causing the crash

    # read dict in the format {"oldcol1name": "newcol1name", "oldcol2name": "newcol2name"}
    rename = {v: k for k, v in toberenamed.items()} 


    # rename columns
    generic_table = table.rename(columns=rename)

    # Write table to new database
    generic_table.to_sql(targettable, targetconn, if_exists="replace")
    targetconn.close()
    sourceconn.close()

我也研究过类似于this one的解决方案,但它们假设您知道列的类型

一个优雅的解决方案将不胜感激

编辑:我知道自9月份发布的3.25.0版以来,sqlite中就有一个方法,但我一直坚持使用2.6.0版


Tags: ofthetoin数据库dbsqlparam
1条回答
网友
1楼 · 发布于 2024-07-04 05:38:28

详细说明我的评论

如果foo.db中有一个表,并且希望将该表的数据复制到bar.db中具有不同列名的新表中:

$ sqlite3 foo.db
sqlite> ATTACH 'bar.db' AS bar;
sqlite> CREATE TABLE bar.newtable(newcolumn1, newcolumn2);
sqlite> INSERT INTO bar.newtable SELECT oldcolumn1, oldcolumn2 FROM main.oldtable;

相关问题 更多 >

    热门问题