减去numpy数组中的第一个值 [英] Subtract from first value in numpy array

查看:999
本文介绍了减去numpy数组中的第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有这样的numpy数组:

Having numpy array like that:

a = np.array([35,2,160,56,120,80,1,1,0,0,1])

我想从数组的第一个元素中减去自定义值(例如5).基本上可以做到:a[0] - 5

I want to subtract custom value (for example, 5) from first element of the array. Basically it can be done like:a[0] - 5

但是如何将结果应用于初始数组,并用答案替换第一个值?

But how can I apply this result to the initial array and replace the first value with the answer?

谢谢!

推荐答案

您可以使用:

a[0] -= 5  # use -=

这会将a变成:

>>> a = np.array([35,2,160,56,120,80,1,1,0,0,1])
>>> a[0] -= 5
>>> a
array([ 30,   2, 160,  56, 120,  80,   1,   1,   0,   0,   1])

对于大多数操作(+-*/等),有一个就地"等效项(+=-=*=/=等等),该操作将与正确的操作数一起应用,然后将其存储回去.

For most operations (+, -, *, /, etc.), there is an "inplace" equivalent (+=, -=, *=, /=, etc.) that will apply that operation with the right operand and store it back.

请注意,如果要减去 all 个元素,则不应该使用Python for循环,这样做有更有效的方法.

Note that if you want to subtract all elements, you should not use a Python for loop, there are more efficient ways for that.

这篇关于减去numpy数组中的第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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