首页 > 解决方案 > 将数据拆分为每 10 个实例并与新数据框连接

问题描述

我有一个数据框 =

Lat    Lon     COG  Sog  status
16.23  23.92   20   14     1004

数据集的长度为 540x5

现在我需要将数据从 row[0] 拆分到 row[9] 即 10x5 并存储到一个新的 DataFrame 中。接下来将数据从row[1]拆分到row[10],即s1,下一个数据从row[2]拆分到row[11],即s2,最多540次迭代。然后连接所有的 DataFrame 并存储到一个新的 DataFrame 中。

标签: pythonpandas

解决方案


您可以尝试以下方法:

设置:

np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,(20,4)),columns=list('ABCD'))

使用列表推导,我们得到如下索引:

[(a,b) for a, b in zip(df.index,df.index[10:])]
#[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), 
#(5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]

同样,只需传递df.ilocthen concat 下的索引:

win = 10 #change the window as required 
final = pd.concat([df.iloc[a:b] for a, b in zip(df.index,df.index[win:])],sort=False)
print(final)

推荐阅读