I am able to do it in two lines for the numpy module:
x=np.zeros(10)
x[4]=1
However, I was wondering if its possible to combine the two together
There are multiple ways to do this. For example, np.arange(10) == 4
gives you an array of all False
values except for one True
at position 4.
Under the covers, NumPy's bool
values are just 0
and 1
as uint8
(just like Python's bool
values are 0
and 1
, although of a unique integral type), so you can just use it as-is in any expression:
>>> np.arange(10) == 4
array([False, False, False, False, True, False, False, False, False, False], dtype=bool)
>>> np.arange(10) * 1
array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0])
>>> np.arange(10) + 23
array([23, 23, 23, 23, 24, 23, 23, 23, 23, 23])
… or view
it as uint8
instead of bool
:
>>> (np.arange(10) == 4).view(np.uint8)
array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=uint8)
… or, if you want normal int
values, you can convert it:
>>> (np.arange(10) == 4).astype(int)
array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0])
And so on.
However, this seems a lot less readable, and it's also about 20% slower in a quick test, so unless you're doing this for code-golfing reasons, why?
x = numpy.array([0,0,0,0,1,0,0,0,0,0])
:P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With