【问题标题】:numpy append to an indexed array (after np.where)numpy 追加到索引数组(在 np.where 之后)
【发布时间】:2017-04-01 04:18:15
【问题描述】:

我想将值附加到选定的数组中,而不必经过 for 循环。

即如果我想将 0 值添加到数组的某些位置:

a=np.array([[1,2,3,4,5],[1,2,3,4,5]])    
condition=np.where(a>2)    
a[condition]=np.append(a[condition],np.array([0]*len(condition[0])))

-> ValueError: shape mismatch: value array of shape (12,) could not be broadcast to indexing result of shape (6,)

编辑澄清:

我需要向选定的数组位置添加值(和维度,如果需要)。循环看起来像这样:

for t in range(len(ind)):
    c = cols[t]
    r = rows[t]
    if data1[r, c] > 2:
        data2[r,c]=np.append(data2[r,c],t)

有什么办法可以消除这个循环(~100 000 次迭代)?谢谢

【问题讨论】:

  • 想要的结果是什么?

标签: python arrays numpy append


【解决方案1】:

让我们看看碎片:

In [92]: a=np.array([[1,2,3,4,5],[1,2,3,4,5]])    
    ...: condition=np.where(a>2)  
    ...: 
In [93]: a
Out[93]: 
array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])
In [94]: condition
Out[94]: 
(array([0, 0, 0, 1, 1, 1], dtype=int32),
 array([2, 3, 4, 2, 3, 4], dtype=int32))
In [95]: a[condition]
Out[95]: array([3, 4, 5, 3, 4, 5])
In [96]: np.append(a[condition],np.array([0]*len(condition[0])))
Out[96]: array([3, 4, 5, 3, 4, 5, 0, 0, 0, 0, 0, 0])

您正在尝试将 12 个值放入 6 个插槽中。没办法!

你期待什么?我认为我什至不应该猜测。继续向我们展示循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2015-02-21
    • 2021-04-15
    • 2016-05-05
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多