python - 如何将非重叠数据帧矢量化为重叠移位数据帧?
问题描述
我想将常规数据帧转换为具有重叠和移位的多索引数据帧。
例如,输入数据帧是这样的示例代码:
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)
有没有办法矢量化和加速这个过程?
谢谢。
解决方案
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
推荐阅读
- django - Django中stealth_options的用例是什么?
- java - 在 AlertDialog 中向 LinearLayout 添加多行
- javascript - 在 NextJS 中使用自定义文档时如何获取 URL 参数
- regex - 部分路径匹配正则表达式
- javascript - 字符串“number”和实数“number”的条件“if”“else”语句
- c# - c#在导出excel中将通用类型转换为日期类型
- python - Python:EEL 和 SELENIUM / 无法创建安装程序
- javascript - 如何使用 GraphQL 处理 long Int?
- python - 如何在 [[ ]] 中获得价值
- java - 领域无法找到删除嵌套对象或内部对象的任何方法