python - 基于行号列表合并数据框
问题描述
我需要将每一行与大型数据帧(> 50000)中的每一行进行比较,导致超过 10 亿次比较,这在 Pandas 数据帧上的计算成本太高。
因此,我将我的值加载到数组中并使用生成器进行比较:
start = df['StartPos'].values.tolist()
end = df['EndPos'].values.tolist()
index = df.index.values.tolist()
a = [(y-x, (i,j)) for i,x in enumerate(start) for j,y in enumerate(end) if (y-x) > 0 and (y-x) <= 2000 and i != j]
if len(a) == 0:
continue
prod_sizes, rows = zip(*a)
row1,row2 = zip(*rows)
现在,对于每个数据框,df
我最终都会得到一个类似的列表
>>> row1
(0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4)
>>> row2
(1, 2, 3, 4, 5, 2, 3, 5, 3, 5, 2, 5, 1, 2, 3, 5)
现在我想df
根据 和 的值row1
合并我的原始数据框row2
。输出数据框应如下所示:
0: columns of row0 | columns of row1
1: columns of row0 | columns of row2
2: columns of row0 | columns of row3
3: columns of row0 | columns of row4
4: columns of row0 | columns of row5
5: columns of row1 | columns of row2
6: columns of row1 | columns of row3
...
15: columns of row4 | columns of row5
是否有基于行号列表的 Pandas 方式来执行此合并操作,还是我应该简单地使用循环并通过 .iloc 访问行并将它们附加到新数据帧?
解决方案
您可以为扩展网格合并分配关键帮助
例如,您有以下数据框
df1=pd.DataFrame({'A':[1,2,3]})
df2=pd.DataFrame({'A':[1,2,3]})
我们merge
用assign
钥匙做
mergedf=df1.assign(key=1).reset_index().merge(df2.assign(key=1).reset_index(),on='key')
mergedf.loc[mergedf.index_y>mergedf.index_x] # filter out the row in df1 greater than row in df2
Out[497]:
index_x A_x key index_y A_y
1 0 1 1 1 2
2 0 1 1 2 3
5 1 2 1 2 3
推荐阅读
- python - 了解 pandas 应用循环行为
- spring-boot - 就绪探测失败,状态码:401
- .net - 如何在 WEB API 应用程序中安全地使用 .NET MQQueueManager?
- javascript - 我应该在数据库查询的哪个阶段返回结果以便能够将它们用作获取响应
- php - 使用 DOM 在 PHP 中解析 XML 文件
- javascript - WebApi 到 Angular 属性键都是小写的?
- c - 指针的值不是地址吗?
- automated-tests - 你觉得 cypress 中调用函数的用处是什么?
- file - SAS 中的文件选项
- php - 按下按钮时在网页中重新排序 SQL 结果