如何在特定范围内向numpy数组添加标量? [英] How to add a scalar to a numpy array within a specific range?

查看:65
本文介绍了如何在特定范围内向numpy数组添加标量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种更简单,更节省内存的方式来单独在numpy中执行以下操作.

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

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

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

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.

推荐答案

您可以按如下方式进行赋值:

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])

这篇关于如何在特定范围内向numpy数组添加标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆