2016-08-18 71 views
0

我有一个“开始日期”和“结束日期”的客户名单。对于任何给定的时间段,我的目标是找到有多少客户我活跃。如果客户的开始日期在x之前,并且结束日期在x之后,则客户处于活动状态。我写的这个蛮力版本:熊猫发现月份列表的日期之间的计数

from datetime import datetime 
import pandas as pd 

#dates of interest 
dates = ['2016-01-31','2016-02-29','2016-03-31','2016-04-30','2016-05-31'] 
dates = [datetime.strptime(x, '%Y-%m-%d') for x in dates] 

#sample records 
df = pd.DataFrame([['A','2016-01-01','2016-04-23'],['B','2016-02-05','2016-04-30'],['C','2016-02-02','2016-05-25']],columns = ['customerId','startDate','endDate']) 
df['startDate'] = pd.to_datetime(df['startDate']) 
df['endDate'] = pd.to_datetime(df['endDate']) 

output = [] 
#is there a better way to do this? 
for currDate in dates: 
    record_count = len(df[(df['startDate']<= currDate) & (df['endDate']>= currDate)]) 
    output.append([currDate,record_count]) 


output = pd.DataFrame(output, columns = ['date','active count']) 

有没有更好的办法找到有多少客户是每一个感兴趣的日期之间的活跃?现在我只是遍历所有的日期,但是这对我来说并不是很“pythonic”。

任何想法或援助,将不胜感激!

回答

1

一种方法是:

In [142]: tf = pd.DataFrame({'dates': dates}) 
In [143]: tf['active_count'] = tf['dates'].apply(lambda x: df[(df['startDate']<= x) & (df['endDate']>= x)].count()) 
In [144]: tf 
Out[144]: 
     dates active_count 
0 2016-01-31    1 
1 2016-02-29    3 
2 2016-03-31    3 
3 2016-04-30    2 
4 2016-05-31    0 
+0

谢谢 - 我希望避免申请为好,也是一个缓慢的建设。如果可能的话,试图想出一种矢量化的方法。 – flyingmeatball

相关问题