Python 如何将标量添加到特定范围内的 numpy 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32542689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:45:38  来源:igfitidea点击:

How to add a scalar to a numpy array within a specific range?

pythonarraysnumpy

提问by ébe Isaac

Is there a simpler and more memory efficient way to do the following in numpy alone.

是否有一种更简单且内存效率更高的方法来单独在 numpy 中执行以下操作。

import numpy as np
ar = np.array(a[l:r])
ar += c
a = a[0:l] + ar.tolist() + a[r:]

It may look primitive but it involves obtaining a subarray copy of the given array, then prepare two more copies of the same to append in left and right direction in addition to the scalar add. I was hoping to find some more optimized way of doing this. I would like a solution that is completely in Python list or NumPy array, but not both as converting from one form to another as shown above would cause serious overhead when the data is huge.

它可能看起来很原始,但它涉及获取给定数组的子数组副本,然后准备两个相同的副本,除了标量加法之外,还要在左右方向上追加。我希望找到一些更优化的方法来做到这一点。我想要一个完全在 Python 列表或 NumPy 数组中的解决方案,但不能同时从一种形式转换为另一种形式,如上所示,当数据很大时会导致严重的开销。

采纳答案by Alexander

You can just do the assignment inplace as follows:

您可以按如下方式进行就地分配:

import numpy as np

a = np.array([1, 1, 1, 1, 1])
a[2:4] += 5
>>> a
array([1, 1, 6, 6, 1])