根据长度将数据帧分为相对均匀的块 [英] Split dataframe into relatively even chunks according to length

查看:45
本文介绍了根据长度将数据帧分为相对均匀的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个函数,将提供的数据帧分成所需大小的块.例如,如果数据帧包含1111行,我希望能够指定400行的块大小,并获得三个较小的数据帧,分别具有400、400和311的大小.是否有方便的功能来完成这项工作?在切片的数据帧上存储和迭代的最佳方法是什么?

I have to create a function which would split provided dataframe into chunks of needed size. For instance if dataframe contains 1111 rows, I want to be able to specify chunk size of 400 rows, and get three smaller dataframes with sizes of 400, 400 and 311. Is there a convenience function to do the job? What would be the best way to store and iterate over sliced dataframe?

示例数据框

import numpy as np
import pandas as pd

test = pd.concat([pd.Series(np.random.rand(1111)), pd.Series(np.random.rand(1111))], axis = 1)

推荐答案

您可以按以下方式使用.groupby.

You can use .groupby as below.

for g, df in test.groupby(np.arange(len(test)) // 400):
    print(df.shape)
# (400, 2)
# (400, 2)
# (311, 2)

这篇关于根据长度将数据帧分为相对均匀的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆