假设我有一个 NxN 值数组,我想通过对这些值进行分箱来对它们进行排序,并且对于每个分箱,返回原始值的副本,仅保留相应的值,并将所有其他值替换为零。例如,如果我有:
x = np.array([[1.1,2.2],[1.2,3.2]])
bins = np.array([1,2,3,4])
然后我想要:
output = [[[1.1,0.0],[1.2,0.0]],[[0.0,2.2],[0.0,0.0]],[[0.0,0.0],[0.0,3.2]]]
到目前为止我所拥有的:
Z = np.shape(x)[0]
Y = np.shape(x)[1]
X = np.shape(bins)[0]-1
output = np.broadcast_to(x, (X,Y,Z))
这将创建一个数组,其中包含每个 bin 的原始副本。然后我想我会使用 np.where 将除正确值之外的所有值设置为 0.0,但是当我尝试思考如何准确地编写它时,我的大脑一片空白,而且我也不确定这是否是最好的方法。
如有任何建议,我们将不胜感激,谢谢。
最佳答案
有点脏,但你可以试试这个
outputs = np.zeros(((len(bins)-1,) + x.shape))
for bin_idx, (inf, sup) in enumerate(zip(bins[:-1:1], bins[1::1])):
outputs[bin_idx][np.where(np.logical_and(x>inf, x<sup))] = x[np.where(np.logical_and(x>inf, x<sup))]
关于python - 按值对 Numpy 数组元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880161/