Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create in one line a null vector of size 10 but the fifth value being 1 using numpy

Tags:

python

numpy

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

like image 390
user3211991 Avatar asked Jan 22 '14 22:01

user3211991


2 Answers

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?

like image 176
abarnert Avatar answered Nov 14 '22 22:11

abarnert


x = numpy.array([0,0,0,0,1,0,0,0,0,0])

:P

like image 33
Joran Beasley Avatar answered Nov 14 '22 23:11

Joran Beasley