【发布时间】:2020-05-20 15:10:42
【问题描述】:
我使用的是 3 维数组,其定义如下:
x = np.zeros((dim1, dim2, dim3), dtype=np.float32)
插入一些数据后,只有在特定列中的值仍然为零时,我才需要应用一个函数。 我感兴趣的列是由这个包含正确索引的数组选择的
scale_idx = np.array([0,1,3])
因此我要做的是使用索引来选择那些行和列。
起初我尝试这样做,前二维使用布尔掩码,第三维使用数组:
x[x[:,:,scale_idx].any(axis =2)] ,scale_idx]
但我收到此错误:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,) (3,)
如果我将最后一个索引更改为 : 我会得到我感兴趣的所有行,但我会得到所有可能的列,我希望最后一个数组将充当索引器,如 @987654321 中所述@。
x[x[:,:,scale_idx].any(axis =2)]
我的scale_idx 应该被解释为列索引器,但实际上被解释为行索引,因此,由于只有 2 行符合条件,但我有 3 个索引,我得到一个 IndexError。
我找到了一种解决方法,使用
x[x[:,:,scale_idx].any(axis =2)][:,:,scale_idx]
但它有点难看,因为它是一个切片,我无法修改原始数组。
有人愿意向我解释我做错了什么吗?
编辑: 感谢@hpaulj,我设法隔离了我需要的单元格,之后我创建了一个与所选值具有相同形状的矩阵,并将这些值分配给被屏蔽的单元格,令我惊讶的是,新值不是我刚刚设置的那些是一些我无法弄清楚它们来自哪里的随机整数。 重现代码:
scale_idx = np.array([0,3,1])
b = x[:,:,scale_idx].any(axis =2)
I, J = np.nonzero(b)
x[I[:,None], J[:,None], scale_idx] #this selects the correct cells
>>>
array([[ 50, 50, 50],
[100, 100, 100],
[100, 100, 100]])
scaler.transform(x[I[:,None], J[:,None], scale_idx]) #sklearn standard scaler, returns a matrix with the scaled values
>>>
array([[-0.50600345, -0.5445559 , -1.2957878 ],
[-0.50600345, -0.25915199, -1.22266904],
[-0.50600345, -0.25915199, -1.22266904]])
x[I[:,None], J[:,None], scale_idx] = scaler.transform(x[I[:,None], J[:,None], scale_idx]) #assign the new values to the selected cells
x[I[:,None], J[:,None], scale_idx] #check the new values
array([[0, 2, 0],
[0, 6, 2],
[0, 6, 2]])
为什么新值与我的预期不同?
【问题讨论】:
-
您能分享一个具有特定尺寸的虚拟示例吗?很难说 20 岁的人该做什么
-
对不起,那个20不应该出现,我已经重构了一点代码,现在应该更清楚了,我仍然无法弄清楚为什么它不起作用。也许不支持布尔掩码加数组索引器?
-
您不能将
int的值设置为浮点数
标签: python arrays numpy multidimensional-array indexing