将pandas数据帧拆分为N个块

时间:2018-02-09 11:10:05

标签: python pandas numpy

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

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

有没有一种聪明的方法可以将python数据帧拆分成多个数据帧,每个数据帧包含父数据帧中特定数量的行

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

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

用法:

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

还有一个更简单的想法:

def chunk(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

用法:

for df_chunk in chunk(df, 100):
    #                     |
    #                     The chunk size
    # your code here

顺便说一句。所有这些都可以在SO上找到,并进行搜索。

答案 1 :(得分:1)

您可以从N计算分割数:

splits = int(np.floor(len(df.index)/N))
chunks = np.split(df.iloc[:splits*N], splits)
chunks.append(df.iloc[splits*N:])

答案 2 :(得分:1)

计算分裂指数:

DbSet

用它们来拆分df:

size_of_chunks =  3
index_for_chunks = list(range(0, index.max(), size_of_chunks))
index_for_chunks.extend([index.max()+1])