之前在华为2022全球AI的比赛上就遇到过数据集过大难以一次加载的问题,当时参加的是CTR赛道光train文件就有1.4G,当时使用read_csv方法直接读取整个文件,CPU和CPU直接拉满一度卡机两分多钟。
这次天池的2023AICAS的数据集也是碰到一样的问题,光点击交互数据就分了四个文件每个文件9.69G,尝试使用sublime打开也卡老半天。而且主办方也说二阶段只能提供CPU使用,但在B站看到有类似加载大数据集的解决方案,遂尝试一下。
- 在
read_csv中声明分块加载,同时使用to_csv把分块后的文件重新保存- 把新csv中声明为float64的列转为float16或float32
- 拼接生成的csv
import pandas as pd
import gc
import glob
import os
# 步骤1:分块读取并保存
chunk_size = 10000
num = 1
# 拆分文件,以10000条切分,round1_user_0共切分出24000个文件
for chunk in tqdm(pd.read_csv('round1_user_0.txt', chunksize=chunk_size)):
chunk.to_csv('chunk' + str(num) + '.csv', index = False)
# 避免内存错误
gc.collect()
num += 1
# 步骤2:把新CSV中类型为64位的列,在可接受数据精度丢失的情况下修改
path = r'E:\Dataset\2023AICAS\new'
all_files = glob.glob(os.path.join(path, "*.csv")
grouped_files = []
for filename in all_files:
chunk = pd.read_csv(filename, index_col=None, header=0)
for col in chunk.columns:
if chunk[col].dtype == 'float64':
chunk[col] = chunk[col].astype('float16')
if chunk[col].dtype == 'int64':
chunk[col] = chunk[col].astype('int8')
gc.collect()
grouped_files.append(chunk)
# 步骤3:拼接CSV
df = pd.concat(group_fies, axis=0, ignore_index=True)
# 步骤3:保存CSV
df.to_csv("new_data.csv")
# df.to_feather("new_data.csv")
# df.to_pickle("new_data.csv")
上述为参考连接给出代码,但在本数据集中所有列被当成一个列读取为object对象,可以通过to_string()转为字符串类型,再使用split提取为list类型按照\分割,存为int8类型