【问题标题】:updating 2D array by array[rows,cols] spec? [duplicate]通过 array[rows,cols] 规范更新二维数组? [复制]
【发布时间】:2019-11-29 20:34:03
【问题描述】:

鉴于您有行和列坐标/索引,我如何同时更新多个单元格...类似于:

 rows_idxs = [.....]
 cols_idxs = [.....]
 ary[rows_idxs, cols_idxs] += 1

 ary[itertools.product(rows_idxs,cols_idxs)] += 1

这些都不行!?

我该怎么做?

【问题讨论】:

  • 我不确定我理解你的意思。你能澄清一下,也许举个例子?

标签: python numpy 2d updates


【解决方案1】:

如果您知道您的 row 和 col 索引没有重复值,则 numpy 替换 itertools.product 将是 np.ix_。请务必注意尾随的下划线。

例如:

a = np.arange(15).reshape(3,5)
a[np.ix_([0,2],[1,3,4])] += 1
a
# array([[ 0,  2,  2,  4,  5],
#        [ 5,  6,  7,  8,  9],
#        [10, 12, 12, 14, 15]])

如果有重复可以和np.add.at一起使用:

例如:

a = np.arange(15).reshape(3,5)
np.add.at(a,np.ix_([0,0,0,2],[0,0,3,4,4]),1)
a
# array([[ 6,  1,  2,  6, 10],
#        [ 5,  6,  7,  8,  9],
#        [12, 11, 12, 14, 16]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    相关资源
    最近更新 更多