【问题标题】:Is there a faster way to achieve the same result? [duplicate]有没有更快的方法来达到相同的结果? [复制]
【发布时间】:2020-02-28 11:25:45
【问题描述】:

我有这个 python 代码:

    for i, num in enumerate(num_arr):
        if num > threshold:
            num_arr[i] = threshold

'num_arr' 是一个用整数填充的简单数组, “阈值”可能从 10 到 100,000 不等。 有没有更快的方法来达到相同的结果?按位运算或类似的东西?

【问题讨论】:

  • 看看np.clipnp.minimum

标签: python numpy processing-efficiency


【解决方案1】:

您可以为此使用.clip(..) [numpy-doc]。例如:

num_arr = num_arr<b>.clip(max=threshold)</b>

例如:

>>> a
array([14, 25,  7, 12,  2])
>>> a.clip(max=10)
array([10, 10,  7, 10,  2])

【讨论】:

  • 是的,它似乎从执行时间缩短了 0.1 秒,这很好。
  • @DanShorlaKi:对于小型阵列,提升不会那么显着。通常,当您以“批量”方式处理大量数据(如 1'000、10'000+ 等元素的数组)时,numpy/pandas 会得到回报。
  • 我发现这与 np.clip array[array > threshold] = threshold 的执行时间大致相同
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 2011-03-24
  • 2016-10-05
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
相关资源
最近更新 更多