我有两个数据框:
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
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
我想要来自 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
我在 DF2.EmpStartDate 和 DF1.StartDate 上使用 merge_asof 然后在 Location 和 StartDate 上进行分组来实现这一点。
但是我得到的结果不正确,因为我只在日期列上合并。我需要合并位置和日期列上的数据框。看起来 merge_asof 不支持在多列上合并。如何合并不同位置组的日期列?
最佳答案
merge_asof
保持left
的大小DataFrame,所以它不能匹配 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())
输出: 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
关于python - 多列上的 Pandas merge_asof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157280/