chunksize、iterator --- Pandas分块处理大文件

该博客介绍了如何利用Pandas的chunksize和iterator参数,分块读取和处理大型CSV或TSV文件。通过指定chunksize,可以避免一次性将整个文件加载到内存中,提高内存效率。同时,可以通过get_chunk方法逐块进行数据操作,如清洗、转换等,最后使用pd.concat将所有块合并为一个完整的DataFrame。这种方法对于处理大规模数据集尤其有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理就是不一次性把文件数据读入内存中,而是分多次

1.指定chunksize分块读取文件

read_csvread_table 有一个 chunksize 参数,用以指定一个块大小(每次读取多少行),返回一个可迭代的 TextFileReader 对象。

table=pd.read_table(path+'kuaishou.txt',sep='\t',chunksize=1000000)
for df in table:
    对df处理
    #如df.drop(columns=['page','video_id'],axis=1,inplace=True)
    #print(type(df),df.shape)打印看一下信息

我这里又对文件进行了划分,分成若干个子文件分别处理(没错,to_csv也同样有chunksize参数)

2.指定iterator=True

iterator=True同样返回的是TextFileReader对象

reader = pd.read_table('tmp.sv', sep='\t', iterator=True)
df=reader.get_chunk(10000)
#通过get_chunk(size),返回一个size行的块
#接着同样可以对df处理

example:

 # 数据读取,因数据量比较大,采用分批加载
    if os.path.exists(file_path):
        data = pd.read_csv(file_path, sep=',', engine='python', iterator=True)  # iterator=True 返回一个TextFileReader对象
        chunk_size = 1000000
        chunks = []
        loop = True
        while loop:
            try:
                chunk = data.get_chunk(chunk_size)      # 通过get_chunk返回一个size条记录。也可以在read_csv的时候不指定iterator=True,指定chunksize=size
                chunks.append(chunk)
                # print('chunks: %d' % len(chunks))
            except StopIteration:
                loop = False
                print('Iteration is stopped.')
        print('Start concat...')
        df = pd.concat(chunks, ignore_index=True)
        print('file %s have %d data' % (filename, df.shape[0]))
        return df
    else:
        print("Don't have this file!")
        return None

https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-read-csv-table

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WGS.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值