我正在尝试将带有8列的大约1200万条记录导入到Python中。由于其庞大的尺寸,我的笔记本电脑内存不足以满足这一要求。现在我尝试将SQL数据导入HDF5文件格式。如果有人可以共享从SQL查询数据的代码片段并以块的形式保存为HDF5格式,那将非常有用。我可以使用任何其他更容易使用的文件格式。
我计划进行一些基本的探索性分析,之后可能会使用pandas创建一些决策树/ Liner回归模型。
import pyodbc
import numpy as np
import pandas as pd
con = pyodbc.connect('Trusted_Connection=yes',
driver = '{ODBC Driver 13 for SQL Server}',
server = 'SQL_ServerName')
df = pd.read_sql("select * from table_a",con,index_col=['Accountid'],chunksize=1000)
答案 0 :(得分:7)
试试这个:
sql_reader = pd.read_sql("select * from table_a", con, chunksize=10**5)
hdf_fn = '/path/to/result.h5'
hdf_key = 'my_huge_df'
store = pd.HDFStore(hdf_fn)
cols_to_index = [<LIST OF COLUMNS THAT WE WANT TO INDEX in HDF5 FILE>]
for chunk in sql_reader:
store.append(hdf_key, chunk, data_columns=cols_to_index, index=False)
# index data columns in HDFStore
store.create_table_index(hdf_key, columns=cols_to_index, optlevel=9, kind='full')
store.close()