2016-08-18 66 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

相關問題