如何将 pandas DataFrame 拆分为多个 DataFrame?

How can I split a pandas DataFrame into multiple dataframes?

我有一个包含 231840 行的数据框。我需要将它分成 161 个单独的 table,每个 table 包含 1440 行,即第一个 table 包含前 1440 行,第二个 table 包含下一个 1440行等等,直到我得到 161 个单独的 tables,总行数为 231840 行。有什么想法吗?

简单使用

import numpy as np

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

在你的情况下,你应该将 3 切换为 df(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]) 

您可以使用 np.array_split 拆分数据帧:

import numpy as np

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

编辑(根据 dfs 中 df 的序号分配新的列):

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