【问题标题】:Speed up for-loop with pointer to dictionary使用指向字典的指针加速 for 循环
【发布时间】:2019-11-15 12:18:45
【问题描述】:

以下 for 循环有效,但需要很长时间。数据框 df_customers 有大约 150 万个条目,dict_customers 大约有 500 000 行。

for i in range(len(df_customers)):
    df_customers.iloc[i, j] = dict_customers[df_customers.iloc[i,k]]

我的问题是:如何加快 for 循环?

Dataframe df_customers 包含客户特征,a.o.客户ID。一位客户有几行(因此每行不是唯一的)。

字典 dict_customers 包含唯一的客户 ID(键)和每位客户的访问次数(值)。

我想向 Dataframe df_customers 添加一个新列 k,其中包含从字典中检索到的访问次数。

我用 df_customers 的 for 循环解决了这个问题: 我是行 j 是访问次数的新列 k 是具有 CustomerID 的现有列

注意:CustomerID 从 100 000 开始。

我尝试了以下理解:

df_customers.j-column = [dict_customers[df_custumers.k-column[i]] for i in range(len(df_customers))]

书面理解代码不起作用。它保持所有值 0(如初始化)。 预期的输出是每个 CustomerID 从字典中访问的客户存储在新的 df_customers 列 k 中。

【问题讨论】:

  • 第一个代码片段中的k 是从哪里得到的?
  • j = df_customers.columns.get_loc('j-column')
  • k = df_customers.columns.get_loc('k-column')

标签: python dataframe dictionary for-loop for-comprehension


【解决方案1】:

我找到了解决办法:

  1. 创建字典值列表(CustomerID 为 顺序):
    list_values = [v for v in dict_customers.values()]

  2. 为此列表创建一个数组(也是为了加快速度):
    array_values = np.array(list_values

  3. 理解返回数组所指向的值 df_customers j 列(并更正,因为 CustomerID 从 100 000 和 0 处的数组索引):
    df_customers['j-column'] = array_values[df_customers.iloc[i,k] - 100000] for i in range(len(df_customers))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多