【发布时间】:2018-10-18 07:50:49
【问题描述】:
我有两个 pandas 数据框:一个包含高级客户,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>
我需要为每个客户创建一个数据结构(我最初选择了一个 dict),以显示向每个高级客户销售的产品。
到目前为止,我使用的是以下 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 万高级客户和已售商品数据框中的数百万行条目。
【问题讨论】:
-
你能添加一些数据样本吗?
-
@jezrael 有没有比添加屏幕截图更简单的方法(我现在可以)?我不认为 stackoverflow 允许创建表格...?
-
最好是在文本中复制数据,最好是使用pandas example
-
顺便说一句,可能需要
merge-df_premium_customer.merge(df_sold, on="CustomerID") -
@jezrael 直到我弄清楚熊猫示例,我快速插入了一些 HTML 表格
标签: python html pandas performance