如何使用pd.read_csv()迭代地浏览文件并保留dtype和其他元信息,就好像我一次读入整个数据集一样?
我需要读入一个太大而无法放入内存的数据集.我想使用pd.read_csv导入文件,然后立即将块附加到HDFStore中.但是,数据类型推断对后续块没有任何了解.
如果存储在表中的第一个块仅包含int,并且后续块包含float,则会引发异常.所以我需要首先使用read_csv遍历数据帧并保留最高的推断类型.另外,对于对象类型,我需要保留最大长度,因为它们将作为字符串存储在表中.
是否存在仅在不读取整个数据集的情况下仅保留此信息的Pandonic方式?
我对 SQL 世界有点陌生,但我正在学习名为Optimizing pandas.read_sql for Postgres 的教程。问题是,我正在处理一个大数据集,类似于教程中的示例,我需要一种更快的方法来执行查询并将其转换为 DataFrame。在那里,他们使用这个函数:
def read_sql_tmpfile(query, db_engine):
with tempfile.TemporaryFile() as tmpfile:
copy_sql = "COPY ({query}) TO STDOUT WITH CSV {head}".format(
query=query, head="HEADER"
)
conn = db_engine.raw_connection()
cur = conn.cursor()
cur.copy_expert(copy_sql, tmpfile) # I want to replicate this
tmpfile.seek(0)
df = pandas.read_csv(tmpfile)
return df
Run Code Online (Sandbox Code Playgroud)
我尝试复制它,如下所示:
def read_sql_tmpfile(query, connection):
with tempfile.TemporaryFile() as tmpfile:
copy_sql = "COPY ({query}) TO STDOUT WITH CSV {head}".format(
query=query, head="HEADER"
)
cur = connection.cursor()
cur.copy_expert(copy_sql, tmpfile)
tmpfile.seek(0)
df = pandas.read_csv(tmpfile)
return df
Run Code Online (Sandbox Code Playgroud)
问题是, …