Pandas合并列,其中日期在某个区间内

3

我有两个数据框 - 一个是给客户打电话的记录,另一个记录了每个客户的活跃服务期限。每个客户可以拥有多个服务,但它们不会重叠。

df_calls = pd.DataFrame([['A','2016-02-03',1],['A','2016-05-11',2],['A','2016-10-01',3],['A','2016-11-02',4],
                        ['B','2016-01-10',5],['B','2016-04-25',6]], columns = ['cust_id','call_date','call_id'])

print df_calls

  cust_id   call_date  call_id
0       A  2016-02-03        1
1       A  2016-05-11        2
2       A  2016-10-01        3
3       A  2016-11-02        4
4       B  2016-01-10        5
5       B  2016-04-25        6

而且
df_active = pd.DataFrame([['A','2016-01-10','2016-03-15',1],['A','2016-09-10','2016-11-15',2],
                          ['B','2016-01-02','2016-03-17',3]], columns = ['cust_id','service_start','service_end','service_id'])


print df_active

  cust_id service_start service_end  service_id
0       A    2016-01-10  2016-03-15           1
1       A    2016-09-10  2016-11-15           2
2       B    2016-01-02  2016-03-17           3

我需要找出每个通话所属的服务ID,通过服务开始和结束日期进行识别。如果一次通话不在日期范围内,则应将其保留在数据集中。

以下是我目前尝试的方法:

df_test_output = pd.merge(df_calls,df_active, how = 'left',on = ['cust_id'])
df_test_output = df_test_output[(df_test_output['call_date']>= df_test_output['service_start']) 
                      & (df_test_output['call_date']<= df_test_output['service_end'])].drop(['service_start','service_end'],axis = 1)

print df_test_output

  cust_id   call_date  call_id  service_id
0       A  2016-02-03        1           1
5       A  2016-10-01        3           2
7       A  2016-11-02        4           2
8       B  2016-01-10        5           3

这将删除所有未在服务日期之间的通话记录。您有什么想法可以在满足条件的情况下合并服务 ID,但保留其余记录吗?
结果应如下所示:
#do black magic

print df_calls

cust_id   call_date  call_id  service_id
0       A  2016-02-03        1         1.0
1       A  2016-05-11        2         NaN
2       A  2016-10-01        3         2.0
3       A  2016-11-02        4         2.0
4       B  2016-01-10        5         3.0
5       B  2016-04-25        6         NaN

1
你可以按照 call_iddf_calls2df_calls 进行连接。 - Asish M.
1个回答

3
您可以使用左连接与 merge
print (pd.merge(df_calls, df_calls2, how='left'))
  cust_id  call_date  call_id  service_id
0       A 2016-02-03        1         1.0
1       A 2016-05-11        2         NaN
2       A 2016-10-01        3         2.0
3       A 2016-11-02        4         2.0
4       B 2016-01-10        5         3.0
5       B 2016-04-25        6         NaN

df_calls2不是一个真正的表格。它是将df_calls和df_service合并后去重的输出结果。它被创建出来是为了展示我尝试的方法不起作用。 - flyingmeatball
嗯,你认为它可以工作,但是正在寻找更好的解决方案? - jezrael
啊,我懂了 - 我明白你的意思,那确实可行,谢谢!之前我一直在探索使用图表 https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.sparse.csgraph.connected_components.html - flyingmeatball

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接