I have this nparray :
[[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.]]
and I want to do something like this :
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]
I try this :
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
but the result is this :
[[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. ]]
not what I want ... any ideas?
Thanks!
martineau
124k29 gold badges181 silver badges319 bronze badges
2 Answers 2
A simple approach would be to iterate over the indices.
Then it'd be possible for you to reuse the same for loop that you showed like this:
for i in range(len(array)):
if array[i][0] == 1:
array[i] = [0.8, 0.2, 0, 0, 0]
...
answered Feb 1, 2019 at 16:33
fzzle
1,4945 gold badges25 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
rjpg
yes sometimes is better to keep it VERY simple :-) 'code' for item in array 'code' was not working ...
If your replacement array has the same shape as your target you can do this:
mask = target[target[:, 0] == 1]
target[mask] = replacements[mask]
here is a simple test
test_target = np.eye(4)
test_target[2:, 0] = 1
replacements = np.ones((4, 4)) * 42
Before using np.where try boolean indexing first. Usually it is what you want.
answered Feb 1, 2019 at 20:05
Mihai Andrei
1,0448 silver badges11 bronze badges
Comments
lang-py