向numpy数组中的所有奇数或偶数索引元素添加数字,无循环 [英] add a number to all odd or even indexed elements in numpy array without loops
本文介绍了向numpy数组中的所有奇数或偶数索引元素添加数字,无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设您的numpy数组为:
Lets say your numpy array is:
A = [1,1,2,3,4]
您可以轻松地做到:
A + .1
A + .1
为每个元素numpy数组添加数字
to add a number to that every element numpy array
我正在寻找一种将数字仅添加到奇数或偶数索引中的方法 A [:: 2] +1
,同时保持整个数组不变.
I am looking for a way to add a number to just the odd or even indexed numbers A[::2] +1
while keeping the entire array intact.
是否可以在没有任何循环的情况下向所有奇数或偶数索引元素添加数字?
Is it possible to add a number to all the odd or even indexed elements without any loops?
推荐答案
In [43]: A = np.array([1,1,2,3,4], dtype = 'float')
In [44]: A[::2] += 0.1
In [45]: A
Out[45]: array([ 1.1, 1. , 2.1, 3. , 4.1])
请注意,这会修改 A
.如果您希望不修改 A
,请先复制 A
:
Note that this modifies A
. If you wish to leave A
unmodified, copy A
first:
In [46]: A = np.array([1,1,2,3,4], dtype = 'float')
In [47]: B = A.copy()
In [48]: B[::2] += 0.1
In [49]: B
Out[49]: array([ 1.1, 1. , 2.1, 3. , 4.1])
In [50]: A
Out[50]: array([ 1., 1., 2., 3., 4.])
这篇关于向numpy数组中的所有奇数或偶数索引元素添加数字,无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文