给定一些数组(或张量):

x = np.array([[0, 1, 0, 0, 0],
              [0, 0, 0, 1, 0],
              [1, 0, 0, 0, 0]])

以及一些维数等于x行数的索引:

idx = np.array([3, 1, 0])  # Index values range from (0: number of columns) in "x"!

现在,如果我想根据索引idx将某个值c添加到x的列中,我将执行以下操作:

x[range(3), idx] += c

得到:

x = np.array([[  0,  1,  0,  c,  0],
              [  0,  c,  0,  1,  0],
              [1+c,  0,  0,  0,  0]])

但是如果我想把xrather中的值c加到every other column index,而不是idx中的精确指数,该怎么办?

预期结果(基于上述示例)应为:

x = np.array([[c, 1+c,  c,   0,  c],
              [c,   0,  c, 1+c,  c],
              [1,   c,  c,   c,  c]])

推荐答案

创建用作掩码的布尔数组:

# set up default mask
m = np.ones(x.shape, dtype=bool)
# update mask
m[np.arange(m.shape[0]), idx] = False
# perform boolean indexing
x[m] += c

输出(c=9):

array([[ 9, 10,  9,  0,  9],
       [ 9,  0,  9, 10,  9],
       [ 1,  9,  9,  9,  9]])

m:

array([[ True,  True,  True, False,  True],
       [ True, False,  True,  True,  True],
       [False,  True,  True,  True,  True]])

Python相关问答推荐

这家einsum运营在做什么?E = NP.einsum(aj,kl-il,A,B)

按照行主要蛇扫描顺序对点列表进行排序

如何销毁框架并使其在tkinter中看起来像以前的样子?

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

具有症状的分段函数:如何仅针对某些输入值定义函数?

使用GEKKO在简单DTE系统中进行一致初始化

优化在numpy数组中非零值周围创建缓冲区的函数的性能

分组数据并删除重复数据

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

Pandas 在最近的日期合并,考虑到破产

删除最后一个pip安装的包

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

在Pandas DataFrame操作中用链接替换'方法的更有效方法

ThreadPoolExecutor和单个线程的超时

形状弃用警告与组合多边形和多边形如何解决

Geopandas未返回正确的缓冲区(单位:米)

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

计算空值

如何过滤组s最大和最小行使用`transform`'

如何使用Azure Function将xlsb转换为xlsx?