2016-08-18 1 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']) 

관심의 각 날짜 사이의 활성 얼마나 많은 고객이 찾을 수있는 더 나은 방법이 있나요 :이의 무력 버전을 작성했습니다? 지금 당장은 모든 데이트를 반복하고 있지만, 저에게는 매우 불쾌감을 느끼지 않습니다.

의견이나 도움을 주시면 감사하겠습니다.

답변

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