通过 array[rows,cols] 规范更新二维数组?
updating 2D array by array[rows,cols] spec?
鉴于您有行和列 coordinates/indexes,我怎样才能同时更新多个单元格...类似 :
rows_idxs = [.....]
cols_idxs = [.....]
ary[rows_idxs, cols_idxs] += 1
或
ary[itertools.product(rows_idxs,cols_idxs)] += 1
这些都不行!?
我该怎么做?
如果您知道您的行和列索引没有重复值,那么 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]])
鉴于您有行和列 coordinates/indexes,我怎样才能同时更新多个单元格...类似 :
rows_idxs = [.....]
cols_idxs = [.....]
ary[rows_idxs, cols_idxs] += 1
或
ary[itertools.product(rows_idxs,cols_idxs)] += 1
这些都不行!?
我该怎么做?
如果您知道您的行和列索引没有重复值,那么 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]])