首页 > 解决方案 > 基于行号列表合并数据框

问题描述

我需要将每一行与大型数据帧(> 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 访问行并将它们附加到新数据帧?

标签: pythonpandasdataframe

解决方案


您可以为扩展网格合并分配关键帮助

例如,您有以下数据框

df1=pd.DataFrame({'A':[1,2,3]})
df2=pd.DataFrame({'A':[1,2,3]})

我们mergeassign钥匙做

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

推荐阅读