首页 > 解决方案 > 如何将非重叠数据帧矢量化为重叠移位数据帧?

问题描述

我想将常规数据帧转换为具有重叠和移位的多索引数据帧。

例如,输入数据帧是这样的示例代码:

import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.arange(0, 12).reshape(-1, 2), columns=['d1', 'd2'], dtype=float)
df.index.name = 'idx'
print(df)

输出:

       d1    d2
idx            
0     0.0   1.0
1     2.0   3.0
2     4.0   5.0
3     6.0   7.0
4     8.0   9.0
5    10.0  11.0

我要输出的是:使其按批次重叠并每次移动一行(添加一列batchid以标记每个班次),如下所示(batchsize = 4):

               d1    d2
idx batchid            
0   0         0.0   1.0
1   0         2.0   3.0
2   0         4.0   5.0
3   0         6.0   7.0
1   1         2.0   3.0
2   1         4.0   5.0
3   1         6.0   7.0
4   1         8.0   9.0
2   2         4.0   5.0
3   2         6.0   7.0
4   2         8.0   9.0
5   2        10.0  11.0

到目前为止我的工作: 我可以让它与迭代一起工作并将它们连接在一起。但这需要很多时间。

batchsize = 4
ds, ids = [], []
idx = df.index.values
for bi in range(int(len(df) - batchsize + 1)):
    ids.append(idx[bi:bi+batchsize])
for k, idx in enumerate(ids):
    di = df.loc[pd.IndexSlice[idx], :].copy()
    di['batchid'] = k
    ds.append(di)
res = pd.concat(ds).fillna(0)
res.set_index('batchid', inplace=True, append=True)

有没有办法矢量化和加速这个过程?

谢谢。

标签: pythonpandasdataframevectorizationshift

解决方案


pd.concat您可以使用a内的列表理解来完成此操作,iloc并将i其用作迭代 a 的变量range。这应该更快:

batchsize = 4
df = (pd.concat([df.iloc[i:batchsize+i].assign(batchid=i) 
                 for i in range(df.shape[0] - batchsize + 1)])
      .set_index(['batchid'], append=True))
df
Out[1]: 
               d1    d2
idx batchid            
0   0         0.0   1.0
1   0         2.0   3.0
2   0         4.0   5.0
3   0         6.0   7.0
1   1         2.0   3.0
2   1         4.0   5.0
3   1         6.0   7.0
4   1         8.0   9.0
2   2         4.0   5.0
3   2         6.0   7.0
4   2         8.0   9.0
5   2        10.0  11.0

推荐阅读