我找到了一个很好的方法:
唯一的问题是,当表变得更大(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版
详细说明我的评论
如果foo.db中有一个表,并且希望将该表的数据复制到bar.db中具有不同列名的新表中:
相关问题 更多 >
编程相关推荐