矢量填充阵列使用numpy

时间:2014-12-16 22:46:04

标签: python numpy

v1 = np.zeros(20) 
v2 = np.zeros(20)

data = [ list of length 20]

for i, ele in enumerate(data):
      if ele.type != 'foo'
           v1[i] = 1
           v2[i] = 20

我不确定这是否是在“矢量”世界中这样做的正确方法??

1 个答案:

答案 0 :(得分:1)

典型的方法是使用boolean index arrays

v1 = np.zeros(20) 
v2 = np.zeros(20)
is_foo = np.asarray([ele.type == "foo" for ele in data])
v1[~is_foo] = 1
v2[~is_foo] = 20

或者,没有提前“分配”数组:

is_foo = np.asarray([ele.type == "foo" for ele in data])
v1 = np.where(~is_foo, 1, 0)
v2 = np.where(~is_foo, 20, 0)