将 Pandas 数据帧拆分为 N 块

Hen*_*sen 5 python numpy pandas

我目前正在尝试将 Pandas 数据帧拆分为包含每 N 行的未知数量的块。

我曾尝试使用 numpy.array_split() 这个功能,但是将数据帧分成 N 个包含未知行数的块。

是否有一种巧妙的方法可以将 python 数据帧拆分为多个数据帧,每个数据帧都包含来自父数据帧的特定行数

Jam*_*ner 6

你可以试试这个:

def rolling(df, window, step):
    count = 0
    df_length = len(df)
    while count < (df_length -window):
        yield count, df[count:window+count]
        count += step
Run Code Online (Sandbox Code Playgroud)

用法:

for offset, window in rolling(df, 100, 100):
    # |     |                      |     |
    # |     The current chunk.     |     How many rows to step at a time.
    # The current offset index.    How many rows in each chunk.
    # your code here
    pass
Run Code Online (Sandbox Code Playgroud)

还有一个更简单的想法:

def chunk(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
Run Code Online (Sandbox Code Playgroud)

用法:

for df_chunk in chunk(df, 100):
    #                     |
    #                     The chunk size
    # your code here
Run Code Online (Sandbox Code Playgroud)

顺便提一句。所有这些都可以通过搜索在 SO 上找到。