该程序获取一些.csv数据库,对它们进行计算操作,然后有必要保存生成的数据库,以便使用Dask.Dataframe读取。在Python中读取上传的文件时,应保留数据帧在循环中的列类型。我假设您需要使用csv文件+一个单独的配置文件来指定列的类型。
另一个问题是,如何在一个数据帧中读取大文件?
主要功能如下:
def LoadDataFromDB(con,table): --In this block, you need to record outgoing
date_str = datetime.now().strftime("%d_%b_%Y_%H_%M_%S")
chunkS = 100
filename = "./genfiles/" + date_str + ".gz"
ExRates = ImportCSV("exchrates/Currency rates.csv")
log = open("logs/log_"+ date_str + ".txt","w+")
pbar = tqdm(total=CountTableRows(con)/chunkS)
dfSQL = pds.read_sql_query((SQL_columns + table + SQL_Where),con,chunksize=chunkS)
for i,chunk in enumerate(dfSQL): --In this loop, after the res function, we save the data to a file
print("Reading a Block of Data...")
res = Calculate(chunk,ExRates,log)
df = dd.from_pandas(res, npartitions=3)
print(chunk.dtypes)
pbar.update()
pbar.close()
log.close()
return filename
假设您使用的是NoSQL数据库,我之前使用以下函数将数据帧保存到数据库中,以将其转换为JSON格式:
def dataframe_to_dict(df: pd.DataFrame) -> Dict[Any, Any]:
data_dict = df.to_dict("list")
d = {"data": data_dict, "dtypes": {col: df[col].dtype.name for col in df.columns}, "index": df.index}
return d
然后在读取数据库时,我使用此函数将其转换回数据帧
def dict_to_dataframe(d: Dict[Any, Any]):
df = pd.DataFrame.from_dict(d["data"])
df.index = d["index"]
for col, dtype in d["dtypes"].items():
df[col] = df[col].astype(dtype)
return df
如果您的数据帧太大,甚至无法放入单个数据帧,那么您可能需要摆弄dask。但这应该有助于你开始。