为了账号安全,请及时绑定邮箱和手机立即绑定

在 numpy 数组中的多个索引上设置值

在 numpy 数组中的多个索引上设置值

HUX布斯 2023-04-18 16:36:39
我有以下 python 代码片段:import numpy as np# Some random arrayx = np.random.rand(34, 176, 256)# Get some indexespos_idx = np.argwhere(x > 0.5)# Sample some values from these indexesseeds = pos_idx[np.random.choice(pos_idx.shape[0], size=5, replace=False), :]# Now create another arrayy = np.zeros_like(x, np.uint8)y[seeds] = 1最后一行给出了如下错误:index 77 is out of bounds for axis 0 with size 34但我不确定这是怎么发生的,因为所有采样索引都应该有效,因为它们是一个子集。
查看完整描述

3 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

它将种子中的值视为第一维的索引。要通过种子中的索引访问元素,您可以使用:

y[seeds[:,0],seeds[:,1],seeds[:,2]] = 1


查看完整回答
反对 回复 2023-04-18
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

此代码将帮助您将值设置为 1


import numpy as np


# Some random array

x = np.random.rand(34, 176, 256)

# Get some indexes

pos_idx = np.argwhere(x > 0.5)

# Sample some values from these indexes

seeds = pos_idx[np.random.choice(pos_idx.shape[0], size=5, replace=False), :]

# Now create another array

y = np.zeros_like(x, np.uint8)

for i in seeds:

    y[tuple(i)] = 1


查看完整回答
反对 回复 2023-04-18
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

种子的形状是否正确?如果我理解正确的话,x有随机值;y与 x 具有相同的形状,但全为零;andseeds是一些索引值,这些位置将被设置为一个。


print('x    : ', x.ndim, x.shape)

print('y    : ', y.ndim, y.shape)

print('seeds: ', seeds.ndim, seeds.shape)


x    :  3 (34, 176, 256)

y    :  3 (34, 176, 256)

seeds:  2 (5, 3)


查看完整回答
反对 回复 2023-04-18
  • 3 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信