我有两个熊猫数据框:一个具有高级客户df_premium_customer
,另一个具有所有已售商品df_sold
,具有列
“ customerID”(包含高级客户和其他客户的ID),“ ArticleID”,“ Date”和其他几个。
df_premium_customer
的外观
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Bordered Table</h2>
<p>Use the CSS border property to add a border to the table.</p>
<table style="width:100%">
<tr>
<th>Premium_CustomerID</th>
</tr>
<tr>
<td>34674324</td>
</tr>
<tr>
<td>18634345</td>
</tr>
<tr>
<td>99744336</td>
</tr>
</table>
</body>
</html>
这是df_sold
的样子
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Bordered Table</h2>
<p>Use the CSS border property to add a border to the table.</p>
<table style="width:100%">
<tr>
<th>CustimerID</th>
<th>ArticleID</th>
<th>Date</th>
</tr>
<tr>
<td>34674324</td>
<td>3467434</td>
<td>20140302</td>
</tr>
<tr>
<td>98674342</td>
<td>3454234</td>
<td>20140822</td>
</tr>
<tr>
<td>74644334</td>
<td>4444434</td>
<td>20150321</td>
</tr>
</table>
</body>
</html>
我需要为每个客户建立一个数据结构(初步选择了一个字典),以显示向每个高级客户出售的产品。
到目前为止,我正在使用以下Python 3代码:
sold_to_customer = {}
for customer in df_premium_customer["CustomerID"]:
#generate the list of indexes of this this customers appears in df_sold
cust_index = df_sold.index[df_sold['CustomerID'] == customer].tolist()
#add this customers as key to the dict
sold_to_customer[customer] = []
for ind in cust_index:
#add the name of the things he bought,when, and for how much as values to this key
sold_to_customer[customer].append(list(df_sold[ind][["ArticleID","Date"]]))
这是减慢速度的方法!
让它运行一点并进行推断需要16个小时才能完成,因为我有30万高级客户,并且在已售商品数据框中有数百万行的条目。
答案 0 :(得分:1)
我相信您的问题来自熊猫。一般来说,熊猫非常慢。通过使用merge或groupby方法,您可能会加快速度,但是我什至不确定。我相信获得加速的一种简单方法就是以numpy的方式完成所有工作。 我认为这行
cust_index = df_sold.index[df_sold['CustomerID'] == customer].tolist()
因为您为每个客户都花了很多钱,所以要花很多钱。
您可以做的是创建一个包含所有高级客户ID的字典,然后浏览所有数据。要遍历所有数据,可以使用for循环,该循环仍然很慢,但我相信比您对熊猫的处理速度快。
sold_to_customer = {}
for customer in df_premium_customer["CustomerID"]:
#Initialize the dict
sold_to_customer[customer] = []
data = df_sold.values
for i,j,k in data:
sold_to_customer[i].append([j,k])
这使您仅浏览一次数据,并且由于对dict的访问应该是快速的,因此您应该很好。 让我知道这是否可以加快速度,并且速度是否足够,还是应该对其进行优化。