我有一个这样的数据帧。
A,B
1,2
3,4
5,6
7,8
9,10
11,12
13,14我想在数据帧上拆分这部分。拆分的数据帧应该每三行包含一次。拆分的第一个数据帧可以包含从索引0到索引2。第二个包含从索引1到索引,依此类推。
A,B
1,2
3,4
5,6
A,B
3,4
5,6
7,8
A,B
5,6
7,8
9,10诸若此类。
我一直在使用forloop,然后使用iloc,然后将这些拆分的dataframe添加到列表中。
我正在寻找是否有一些矢量化方法来在pandas中拆分上述数据帧。数据帧很大,使用forloop遍历每一行都很慢。
发布于 2020-12-21 22:14:32
假设您有标准的RangeIndex索引,并借用了滚动窗口from here的矢量化方法,我们可以得到numpy的级别:
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
df.to_numpy()[rolling_window(df.index.values, 3)]哪一项会产生
array([[[ 1, 2],
[ 3, 4],
[ 5, 6]],
[[ 3, 4],
[ 5, 6],
[ 7, 8]],
[[ 5, 6],
[ 7, 8],
[ 9, 10]],
[[ 7, 8],
[ 9, 10],
[11, 12]],
[[ 9, 10],
[11, 12],
[13, 14]]])如果需要将它们作为数据框返回,只需使用构造函数和map
map(pd.DataFrame, df.to_numpy()[rolling_window(df.index.values, 3)])https://stackoverflow.com/questions/65394175
复制相似问题