Pandas合并日期之间的列

时间:2016-11-16 15:16:32

标签: python pandas

我有两个数据帧 - 一个是向客户发出的呼叫,另一个是由客户端识别活动服务的持续时间。每个客户端可以有多个服务,但它们不会重叠。

Uncaught (in promise) Error: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`. Check the render method of bound createElement.(…)

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

我需要找到每个调用所属的service_id,由service_start和service_end日期标识。如果呼叫不在日期之间,则它们应保留在数据集中。

这是我到目前为止所尝试的内容:

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

这会丢弃所有不在服务日期之间的呼叫。有关如何在满足条件的service_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

1 个答案:

答案 0 :(得分:3)

您可以在左连接中使用merge

private void setupDialogBackground() {
    getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            FrameLayout bottomSheet = (FrameLayout) d.findViewById(R.id.design_bottom_sheet);
            if (bottomSheet == null)
                return;
            bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
            bottomSheet.setBackground(null);
        }
    });
}