Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何优化创建DICT列表的for循环?_Python_Pandas_Performance_Parallel Processing - Fatal编程技术网

Python 如何优化创建DICT列表的for循环?

Python 如何优化创建DICT列表的for循环?,python,pandas,performance,parallel-processing,Python,Pandas,Performance,Parallel Processing,我有下面的循环,它进行了约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]["phon

我有下面的循环,它进行了约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对其进行并行化。还有其他推荐/更好的方法吗?

请使用检查哪些是慢行

瓶颈往往不在你认为的地方

您可以调整的一件事是一次查找100个客户ID,然后分块处理。这通常会减少开销


然后,您可以对它进行很好的平衡,例如,以1000块为单位进行查找,并使用具有多处理的共享列表来附加JSON。发布line_profiler的结果后,我们可以讨论如何执行此操作。

您这样问是因为它太慢了吗?循环中的第一行对我来说似乎很可疑-我不了解细节,但迭代所有唯一的客户id,然后再次为每个id查找所有具有该id的客户似乎是浪费。为什么不直接迭代所有客户并在循环中根据需要使用他们的id呢?是的,这很慢。根据
tqdm
的规定,这将需要5个小时以上的时间。对于每个
customer\u id
,在
dataset
中可以有许多行,所有这些行都是
device\u id=customer\u data[“device\u id”]行所需的。unique()
什么是
.iloc[0]
意思?它只是从
pandas
数据框中选择第一行,因为对于每个
customer\u id
,所有行都有相同的
标签
电话号码
电子邮件地址
,但不同的
设备id
s。我想你应该使用类似于
数据集.groupby('customer\u id')
,但我不知道如何使用。