2017-12-16 3 views
2

나는 여러 고객으로부터 여러 송장을 포함하는 pandas.DataFrame을 가지고 있습니다. 나는 고객에 따라 두 송장 사이의 시간을 계산하는 우아한 방법을 찾고 싶습니다.색인, 여러 송장의 시간 차이를 얻는 방법 - 팬더

  CustomerID   InvoiceDate time between 2 orders 
index         
536365  17850.0 2010-12-01 08:26:00 0 minutes (or np.nat) 
536366  17850.0 2010-12-01 08:28:00 2 minutes 
536367  13047.0 2010-12-01 08:34:00 0 minutes (It's a new customer) 
536369  13047.0 2010-12-01 08:35:00 1 minute 
536371  13748.0 2010-12-01 09:00:00 0 minute (new customer) 
536372  17850.0 2010-12-01 09:01:00 33 minutes (see line #2) 
536373  17850.0 2010-12-01 09:02:00 1 minute 
536374  15100.0 2010-12-01 09:09:00 0 minute 

이것은 내가 지금까지 발견 것입니다 (하지만 분명히 작동하지 않습니다 다음과 같이

내 데이터 프레임의 모양 (인덱스가 송장 번호입니다, 마지막 열은 내가 기대하고있는 무슨이다) !)

df = df.sort_values(['CustomerID', 'InvoiceDate']) #To order first according 
df = df.set_index('index', drop = True) 
for CustomerID in df['CustomerID'].unique(): 
    index = df.set_index('CustomerID').index.get_loc(CustomerID) 
    df['Ordersep'].iloc[index] = df['InvoiceDate'].iloc[index].diff() 

나에게 도움이 될만한 아이디어가 있습니까?

답변

2

당신은 diff()groupby()를 사용할 수 있습니다

df.InvoiceDate = pd.to_datetime(df.InvoiceDate) 
df["timedelta"] = df.groupby(["CustomerID"]).InvoiceDate.apply(lambda x: x.diff()) 

df 
    index CustomerID   InvoiceDate timedelta 
0 536365  17850.0 2010-12-01 08:26:00   NaT 
1 536366  17850.0 2010-12-01 08:28:00  00:02:00 
2 536367  13047.0 2010-12-01 08:34:00   NaT 
3 536369  13047.0 2010-12-01 08:35:00  00:01:00 
4 536371  13748.0 2010-12-01 09:00:00   NaT 
5 536372  17850.0 2010-12-01 09:01:00  00:33:00 
6 536373  17850.0 2010-12-01 09:02:00  00:01:00 
7 536374  15100.0 2010-12-01 09:09:00   NaT 
+0

빙고! 이 솔루션을 보게되면 언제나 확실 해 보입니다. –

0

이는

for customer_id in df.CustomerId.unique(): 
    matching_customer_mask = df.CustomerId == customer_id 
    customer_df = df[matching_customer_mask] 

    order_times = customer_df.InvoiceDate 
    prev_order_times = customer_df.InvoiceDate.shift(1) 

    df.loc[matching_customer_mask, 'Ordersep'] = order_times - prev_order_times 

이 아래로 인보이스 날짜 열 한 단계 이동 이것이 수행입니다 (아마도 약간의 조정과 함께) 당신이 이전에이로 고객 ID와 송장 날짜에 분류 한 것으로 가정 작동합니다 원하는 차이를 계산합니다.

관련 문제