如何将一个pandas DataFrame分割成多个数据帧?[重复]

问题描述 投票:0回答:1

我有一个由231840行组成的数据框架。我需要将其分割成161个独立的表,每个表包含1440行,即第一个表包含前1440行,第二个表包含下一个1440行,以此类推,直到我得到161个独立的表,合并的行数为231840行。有什么好办法吗?

python pandas dataframe split rows
1个回答
1
投票

你可以用 np.array_split 来分割数据帧。

import numpy as np

dfs = np.array_split(df, 161) # split the dataframe into 161 separate tables

编辑 (要根据数据框中df的顺序数分配一个新的col,可以在数据框中选择一个新的col。dfs):

dfs = [df.assign(new_col=i) for i, df in enumerate(dfs, 1)]

0
投票

只需使用

import numpy as np

df_list = np.array_split(df, 3) # replace 3 with the amount of rows you want

在你的情况下,你应该切换 3df(len) // desired_row_amount. 我们使用 // 将结果四舍五入为一个整数。或者用老式的 for 循环,类似于。

rows = 100  # example number of rows
df_list = []  # list to store dfs

for i in range(len(df) // rows):
    if i == len(df) // rows:  # if this is the last part of the df
        df_list.append(df[i*rows:])  # append the dataframe rows left
    else:
# append with a dataframe which has the desired amount of rows
        df_list.append(df[i*rows:(i+1)*rows]) 
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.