Python 替换元素np数组

Python 替换元素np数组,python,arrays,numpy,Python,Arrays,Numpy,我有一个计划: [[0. 0. 0. 0. 1.] [1. 0. 0. 0. 0.] [0. 0. 1. 0. 0.] ... [0. 0. 1. 0. 0.] [0. 0. 0. 0. 1.] [1. 0. 0. 0. 0.]] 我想这样做: for item in array : if item[0] == 1: item=[0.8,0.20,0,0,0] elif item[1] == 1: it

我有一个计划:

[[0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 ...
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0.]]
我想这样做:

for item in array :
        if item[0] == 1:
            item=[0.8,0.20,0,0,0]
        elif item[1] == 1:
            item=[0.20,0.80,0,0,0]
        elif item[3] == 1:
            item=[0,0,0,0.8,0.2]
        elif item[4] == 1:
            item=[0,0,0,0.2,0.8]
        else:
            [0,0,1,0,0]
我试试这个:

def conver_probs2(arg):
    test= arg
    test=np.where(test==[1.,0.,0.,0.,0.], [0.8,0.20,0.,0.,0.],test)
    return test
但结果是:

[[0.  0.2 0.  0.  1. ]
 [0.8 0.2 0.  0.  0. ]
 [0.  0.2 1.  0.  0. ]
 ...
 [0.  0.2 1.  0.  0. ]
 [0.  0.2 0.  0.  1. ]
 [0.8 0.2 0.  0.  0. ]]
不是我想要的。。。有什么想法吗


谢谢

一个简单的方法是迭代索引

然后,您可以重复使用您显示的相同for循环,如下所示:

for i in range(len(array)):
  if array[i][0] == 1:
    array[i] = [0.8, 0.2, 0, 0, 0] 
  ...

如果替换阵列的形状与目标阵列的形状相同,则可以执行以下操作:

mask = target[target[:, 0] == 1]
target[mask] = replacements[mask]
这里有一个简单的测试

test_target = np.eye(4)
test_target[2:, 0] = 1
replacements = np.ones((4, 4)) * 42

在使用np.where之前,请先尝试布尔索引。通常这是您想要的。

是的,有时最好保持非常简单:-)数组中项的“代码”不起作用。。。