If the input is zero I want to make an array which looks like this:
[1,0,0,0,0,0,0,0,0,0]
and if the input is 5:
[0,0,0,0,0,1,0,0,0,0]
For the above I wrote:
np.put(np.zeros(10),5,1)
but it did not work.
Is there any way in which, this can be implemented in one line?
I'm not sure the performance, but the following code works and it's neat.
Taking a quick look at the manual, you will see that
np.put
does not return a value. While your technique is fine, you are accessingNone
instead of your result array.For a 1-D array it is better to just use direct indexing, especially for such a simple case.
Here is how to rewrite your code with minimal modification:
Here is how to do the second line with indexing instead of
put
:The
np.put
mutates its array arg in-place. It's conventional in Python for functions / methods that perform in-place mutation to returnNone
;np.put
adheres to that convention. So ifa
is a 1D array and you dothen
a
will get replaced byNone
.Your code is similar to that, but it passes an un-named array to
np.put
.A compact & efficient way to do what you want is with a simple function, eg:
output