将数据帧拆分为多个,并重叠行

时间:2019-05-03 07:02:27

标签: python pandas dataframe

一个数据帧,需要将其拆分为多个数据帧。每6行(自上而下)变成一个新的数据帧。

下面的行可以很好地用作屏幕截图。

import pandas as pd

data = {'ID': ["a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a11","a12","a13","a14","a15","a16","a17","a18","a19","a20","a21","a22"], 
'Unit_Weight': [178,153,193,195,214,157,205,212,219,166,217,186,170,207,204,201,179,215,213,170,217,199]}

df = pd.DataFrame(data)

size = 6      # 6 rows in a new data-frame
list_of_dfs = [df.loc[i:i+size-1,:] for i in range(0, len(df),size)]

for l_d in list_of_dfs:
    print l_d

现在,我想从头开始,并且由于df_2,它包括上一个数据帧的最后2行。

在Python中实现它的正确方法是什么?谢谢。

enter image description here

2 个答案:

答案 0 :(得分:4)

这对我有用:-

angle

答案 1 :(得分:1)

我会向前工作,但只向后计算数据帧编号。

df_num = 5
li_dicts = {}

for x in range(0,17,4):
    y = x + 6
    df_temp = df.iloc[x:y,:]
    li_dicts[("df_" + str(df_num))] = df_temp
    df_num -= 1

li_dicts['df_5']

   ID  Unit_Weight
0  a1          178
1  a2          153
2  a3          193
3  a4          195
4  a5          214
5  a6          157