我有一个包含231840行数据的数据框。我需要将其分成161个独立的表格,每个表格包含1440行,即第一个表格包含前1440行,第二个表格包含接下来的1440行,以此类推,直到得到161个独立表格,总行数为231840行。有什么想法吗?
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)]
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])
df['new_col'] = [i for i, df in enumerate(dfs, 1) for _ in range(len(df))]
这个怎么样? - Shubham Sharma