为numpy数组切片的奇数和偶数元素分配不同的值

时间:2019-02-20 05:46:07

标签: python numpy

是否可以为numpy数组切片的偶数和奇数元素分配不同的值?

将起作用的代码示例:

a=np.zeros(100)
b=np.arange(10,50,10)

print(a)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0.]

a[b]=10

print(a)

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0. 10.  0.  0.  0.  0.  0.  0.  0.
  0.  0. 10.  0.  0.  0.  0.  0.  0.  0.  0.  0. 10.  0.  0.  0.  0.  0.
  0.  0.  0.  0. 10.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

现在,我正在尝试为切片a [b]的偶数和奇数元素分配不同的数字

a[b][::2] = 10

a[b][1::2] = -10

但这不起作用,初始的零数组不会修改。

简短通知-实际上,b和a是动态生成的,因此我通常不知道它们的形状(a和b)以及哪些索引在(b)以内

1 个答案:

答案 0 :(得分:0)

您应直接为b编制索引:

import numpy as np

a = np.zeros(100)
b = np.arange(10,50,10)

a[b[::2]] = 10
a[b[1::2]] = -10

print(a[b])
# [ 10. -10.  10. -10.]