我有2个 Dataframe df1, df2
。df1
由3列start, end, id
组成。df2
由4列start, end, id, quantity
组成。请注意,start < end
始终用于两个 Dataframe 。
对于df1
,每行的end - start
总是15,并且每行的[start, end]
对对于每个id是不重叠的和连续的,例如,
df1:
id start end
1 0 15
1 15 30
1 30 45
2 0 15
2 15 30
2 30 45
我需要在df1
中创建第4列quantity_average
,其中每行的quantity_average
是所有df2.quantity
的 * 加权 * 平均值,以便两个 Dataframe 中对应的id
相同,并且两个 Dataframe 中的开始、结束对之间存在完全/部分重叠。
权重被定义为(min(df2.end, df1.end) - max(df2.start, df1.start)) / 15
,即,与重叠量成比例。
我将提供一个完整的示例。我们将使用上面的df1
,并使用
df2 =
id start end quantity
1 0 1.1 3.5
1 1.1 11.4 5.5
1 11.4 34 2.5
1 34 46 3
2 0 1.5 2.2
2 1.5 20 1.0
2 20 30 4.5
因此,quantity_average
的结果为:
1.1 / 15 * 3.5 + (11.4 - 1.1)/15 * 5.5 + (15 - 11.4) / 15 * 2.5 = 4.63333
(30 - 15) / 15 * 2.5 = 2.5
(34 - 30) / 15 * 2.5 = 0.66666
1.5 / 15 * 2.2 + (15 - 1.5) / 15 * 1.0 = 1.12
(20 - 15) / 15 * 1.0 + (30 - 20) / 15 * 4.5 = 3.33333333333
0
我想知道是否有一种快速的方法可以在Pandas身上做到这一点?
1条答案
按热度按时间toe950271#
这里有一个(不那么简单)的方法。它的速度很快,因为它使用矢量化函数,但它的时间和内存复杂度都是
O(len(df1) * len(df2))
。根据数据集的规模,内存需求可能会超过计算机硬件。其思想是使用numpy广播将
df1
中的每一行与df2
中的每一行进行比较,搜索满足以下条件的对:id
start - end
)。...然后对它们执行计算: