add a number to all odd or even indexed elements in numpy array without loops

前端 未结 4 1223
后悔当初
后悔当初 2021-02-07 14:30

Lets say your numpy array is:

 A =    [1,1,2,3,4]

You can simply do:

A + .1

to add a number to tha

4条回答
  •  被撕碎了的回忆
    2021-02-07 14:50

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

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

提交回复
热议问题