我有一个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()


有什么办法可以帮助我吗?

最佳答案

您可以将groupby()diff()一起使用:

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

关于python - 如何获取索引和多张发票之间的时差- Pandas ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47841502/

10-14 13:24