【问题标题】:Pandas: speed up iterating throught two dataframesPandas:加速遍历两个数据帧
【发布时间】:2019-08-23 18:20:55
【问题描述】:

我有一个 DataFrame B,它有列:id_number, performance, min_value, max_value

B
id_number | perfomance | min_value | max_value
12        | A          | 400       | 700
4         | B          | 1000      |1250
89        | C          |1          | 30

我想创建一个字典,方法如下:

for idx, r in B.iterrows():
  for i in range(r['min_value'], r['max_value'] + 1):
      dic[i] = r[id_number]

(注意,id_number 不是唯一的。)

我的数据框 B 非常大(> 5M 记录),并且 min 和 max 之间的范围通常非常大(数千),因此整个过程需要很长时间。有没有办法更快地实现上述字典创建?

【问题讨论】:

  • 范围 [minvalue, maxvalue] 都是唯一的?
  • 是的,确实它们都是独一无二的
  • 您创建的 dict 的目的是什么,您将如何使用它?我之所以这么问,是因为我认为优化您已有的代码并创建相同的字典可能非常困难,但如果您最终根本不需要字典,可能会找到一种方法。

标签: pandas performance loops dictionary for-loop


【解决方案1】:

试试这个:

dic = (df.apply(lambda x: pd.Series(x['id_number'], 
                                    index = np.arange(x['min_value'], x['max_value']+1)),
                axis=1)
         .stack()
         .reset_index(level=0, drop=True)
         .to_dict())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多