【发布时间】:2018-04-09 15:33:40
【问题描述】:
我正在尝试对每个产品销售日和产品 ID 的一些销售数据进行排序,然后我想用 pandas 计算一些统计数据。有没有一种有效的方法来做到这一点?我的数据集有数百万行。
数据集如下所示(df1, 3.000.000 + rows):-------------------------------- ---------------------------------------------
|productID |productCategory |expiryDate |Price |Currency |quantitySold| daySold|
|Fdgd4 |Ergdgf |15sep2020 00:00:00 |125 |USD |5675 |18feb2017 12:45:17|
|Sd23454 |sdfdsr |17mar2018 00:00:00 |39 |USD |654 |31jan2017 12:45:17|
|Fdgd4 |Ergdgf |15sep2020 00:00:00 |125 |USD |300 |18feb2017 09:17:15|
|Sd23454 |sdfdsr |17mar2018 00:00:00 |39 |USD |200 |31jan2017 15:30:35|
|Rt4564 |fdgdf |13jun2018 00:00:00 |45 |USD |1544 |31feb2017 13:25:31|
|Fdgd4 |Ergdgf |15sep2020 00:00:00 |125 |USD |4487 |18mar2017 09:17:15|
|Sd23454 |sdfdsr |17mar2018 00:00:00 |39 |USD |7895 |31aug2017 15:30:35|
我想每天对每个 productID 进行排序计算一些简单的统计数据。所以我认为我的代码应该首先每天订购行,然后按产品订购。然后它应该计算统计数据并将它们添加到表中。
本例中的结果是(df2):
|productID |productCategory |expiryDate |Price |Currency |quantitySold |daySold |volSTD |totalVol |totalRevenue|
------------------------------------------------------------------------**
|Sd23454 |sdfdsr |17mar2018 00:00:00 39 |USD |654 |31jan2017 12:45:17 |321.02 |854 |33306 |
|Fdgd4 |Ergdgf |15sep2020 00:00:00 125 |USD |300 |31jan2017 15:30:35 |0 |300 |37500 |
|Fdgd4 |Ergdgf |15sep2020 00:00:00 125 |USD |5675 |18feb2017 12:45:17 |840.04 |10162 |1270250|
|Rt4564 |fdgdf |13jun2018 00:00:00 45 |USD |1544 |31feb2017 13:25:31 |0 |544 |69480 |
|Sd23454 |sdfdsr |17mar2018 00:00:00 39 |USD |7895 |31aug2017 15:30:35 |0 |7895 |307905 |
我在 pandas 中使用了一个嵌套的 for 循环,它给出了预期的结果,但它确实需要很长时间(几个小时)。 我正在寻找一种快速获得此结果的方法。
我的代码(可能是你见过的最糟糕的代码):
uniqueDays = df1.daySold.unique()
numberOfDays = df1.shape[0]
df_results = pd.Dataframe(columns=[‘productID’, ‘productCategory’, ‘expiryDate Price’, ‘Currency’, ‘quantitySold’, ‘daySold’, ‘volSTD’, ‘totalVol’, ‘totalRevenue’])
For i in range(0, numberOfDays):
temp1 = df1.loc[df1[‘daySold’]== uniqueDays[i]]
uniqueID = temp1.productID.unique()
NumberOfUniqueID = uniqueID.shape[0]
for j in range(0, NumberOfUniqueID):
temp2 = temp1.loc[temp1[‘daySold’]== uniqueID[j]
volSTD = temp2.quantitySold.std()
totalVol = temp2.quantitySold.sum()
totalRevenue = temp2.quantitySold.dot(temp2.price)
temp3 = temp2.iloc[0] # it does not matter which row I pick
temp3[‘volSTD’] = volSTD
temp3[‘totalVol’] = totalVol
temp3[‘totalRevenue’] = totalRevenue
df_results = df_results.append(temp3)
这给了我想要的结果,但它太慢了。特别是将列(volSTD、totalVol 和 totalRevenue)添加到 temp3 并将 temp3 附加到 df_results 总共需要 81.3% 的处理时间。
有没有人有更快的方法来做到这一点?使用向量?还是填充现有数据框而不是追加?
谢谢
【问题讨论】:
-
你看过
groupby吗?这听起来像是一个清晰的groupby工作流程。