我有以下循环,进行约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对其进行并行化。还有其他推荐/更好的方法吗?
答案 0 :(得分:1)
请使用https://github.com/rkern/line_profiler检查哪些是慢行。
通常瓶颈不在您认为的所在。
您可以调整的一件事是一次查找说100个customer_id,然后分块处理。这通常会减少开销。
然后,您可以在其中保持良好的平衡,例如查找1000个大块,并使用带有多处理功能的共享列表来附加JSON。一旦发布了line_profiler的结果,我们就可以讨论如何做。