多列上的 Pandas merge_asof

sks*_*sks 6 python pandas

我有两个数据框:

DF1:

StartDate      Location

2013-01-01     20000002
2013-03-01     20000002
2013-08-01     20000002
2013-01-01     20000003
2013-03-01     20000003
2013-05-01     20000003
2013-01-01     20000043
Run Code Online (Sandbox Code Playgroud)

DF2:

EmpStartDate   Location

2012-12-17     20000002.0 
2013-02-25     20000002.0 
2013-06-26     20000002.0 
2012-09-24     20000003.0 
2013-01-07     20000003.0 
2013-07-01     20000043.0
Run Code Online (Sandbox Code Playgroud)

我想要来自 DF2 的计数,其中 DF1.Location = DF2.Location 和 DF2.EmpStartDate<=DF1.StartDate

输出:

StartDate      Location   Count

2013-01-01     20000002   1
2013-03-01     20000002   2
2013-08-01     20000002   3
2013-01-01     20000003   1
2013-03-01     20000003   2
2013-05-01     20000003   2
2013-01-01     20000043   0
Run Code Online (Sandbox Code Playgroud)

我在 DF2.EmpStartDate 和 DF1.StartDate 上使用 merge_asof 然后在 Location 和 StartDate 上进行分组来实现这一点。但是我得到的结果不正确,因为我只在日期列上合并。我需要合并位置和日期列上的数据框。看起来 merge_asof 不支持在多列上合并。如何合并不同位置组的日期列?

ALo*_*llz 4

merge_asof维护 DataFrame 的大小left,因此它无法将 中的同一行left与 中的多行匹配right

一种简单但可能内存效率低下的计算方法是执行一次大merge运算Location,然后计算有多少行df.EmpStartDate < df.StartDate

df = df1.merge(df2)
(df.assign(Count = df.EmpStartDate < df.StartDate)
   .groupby(['StartDate', 'Location'])
   .Count.sum()
   .astype('int')
   .reset_index())
Run Code Online (Sandbox Code Playgroud)

输出:

   StartDate  Location  Count
0 2013-01-01  20000002      1
1 2013-01-01  20000003      1
2 2013-01-01  20000043      0
3 2013-03-01  20000002      2
4 2013-03-01  20000003      2
5 2013-05-01  20000003      2
6 2013-08-01  20000002      3
Run Code Online (Sandbox Code Playgroud)