Issue
Hello python community,
I am new to python and playing around with numpy arrays and have a question. E.g. I have this 3D array (in reality the array is much much bigger)
input = np.array([[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]],[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]]])
and I want to replace the 2s with 0s to get:
result = np.array([[[0,0,1,1,0,0],[0,0,1,1,0,0],[0,0,1,1,0,0]],[[0,0,1,1,0,0],[0,0,1,1,0,0],[0,0,1,1,0,0]]])
Is there an efficient/fast way to do this?
The only thing I know is to iterate with for x in range ...
but that's probably not very efficient is it?
Solution
Try:
inp = np.array(
[
[[0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2]],
[[0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2]],
]
)
inp = np.where(inp == 2, 0, inp)
print(inp)
Prints:
[[[0 0 1 1 0 0]
[0 0 1 1 0 0]
[0 0 1 1 0 0]]
[[0 0 1 1 0 0]
[0 0 1 1 0 0]
[0 0 1 1 0 0]]]
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.