如何优化创建字典列表的循环?



我有以下循环,它进行~300万次迭代。

json_data = []
for customer_id in tqdm(dataset["customer_id"].unique()):
customer_data = dataset[dataset["customer_id"] == customer_id]
label = customer_data.iloc[0]["label"]
phone_number = customer_data.iloc[0]["phone_number"]
email_address = customer_data.iloc[0]["email_address"]
device_ids = customer_data["device_id"].unique()
json_data.append(
{
"uid": f"_:{int(customer_id)}",
"customer_id": int(customer_id),  # int64 -> int
"label": label,
"has_phone_number": [
{"uid": f"_:{phone_number}", "phone_number": phone_number}
],
"has_email_address": [
{"uid": f"_:{email_address}", "email_address": email_address}
],
"has_device_id": [
{"uid": f"_:{device_id}", "device_id": device_id}
for device_id in device_ids
],
}
)

优化这一点的最佳方法是什么?理解会更好吗?我也考虑过使用 joblib 并行化它。还有其他推荐/更好的方法吗?

请使用 https://github.com/rkern/line_profiler 检查哪些是慢线。

通常瓶颈不在你认为的地方。

您可以调整的一件事是一次查找 100 customer_ids并分块处理。这通常会减少开销。

然后,您可以对其进行良好的平衡,例如,以 1000 个块查找并使用具有多处理的共享列表来附加 JSON。一旦您发布了line_profiler的结果,我们就可以讨论如何做到这一点。

最新更新