python - 如何获取索引、多张发票之间的时间差 - Pandas

标签 python pandas diff timedelta

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

相关文章:

python - Django查找文件路径问题

python - 从 pandas resample 对象中删除空的 DataFrame

python - 向图中添加多条 hline

algorithm - 网页更新检测算法

git - 在 git 中显示每个作者更改的行数

python - Google App Engine 中的 Django 模板语法错误

python - 为什么 python 库 "python-pptx"没有获取所有选择数据?

python for循环范围(bigint)

python - 有没有办法在不满足条件的情况下替换值以避免 nan?

c# - 文本差异算法