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

Question:

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

Asked By: user3211991

||

Answers:

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

😛

Answered By: Joran Beasley

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?

Answered By: abarnert

I don’t that it is possible to combine:

x=np.zeros(10) #1 create an array of values 
x[4]=1         #2 assign at least one value of an array a different value

in one line.

Naive:

x = np.zeros(10)[4] = 1 # Fails

fails as value of x is 1 due how python handles chained assignment. Both x and element 4 in array of zeros are assigned value 1.

Therefore, we need to first create an array of zeros, and then assign element assign element 4 a value of 1, and these two cannot be done in one line.

Answered By: Akavall

If you need to do this to multiple elements:

my_vect = np.zeros(42)
# set index 1 and 3 to value 1
my_vect[np.array([1,3])] = 1
Answered By: Ivan Bilan
array = numpy.eye( array_size )[ element_in_array_which_should_be_1 - 1 ]

So to create a null vector of size 10 but the fifth value being 1 in one line is

array = numpy.eye( 10 ) [ 5 - 1 ]

===> array([0., 0., 0., 0., 1., 0., 0., 0., 0., 0.])

🙂

Answered By: Venugopal
b=np.array([int(x==4) for x in range(10)])
print(b)


[0 0 0 0 1 0 0 0 0 0]
Answered By: upendra jena

Use this
np.where(np.arange(10)==4,1,0)

Answered By: Tejas Rangle
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.