user3211991
user3211991

Reputation: 461

How to create in one line a null vector of size 10 but the fifth value being 1 using 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

Upvotes: 5

Views: 14937

Answers (8)

Ananda Chaudhary
Ananda Chaudhary

Reputation: 11

Create a null vector of size 10 but the fifth value which is 1.

import numpy
x = np.zeros(10, dtype=int)
if x[5] == 0:
   x[5] = 1  
print(x)

Upvotes: 1

Tejas Rangle
Tejas Rangle

Reputation: 21

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

Upvotes: 2

upendra jena
upendra jena

Reputation: 11

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


[0 0 0 0 1 0 0 0 0 0]

Upvotes: 1

Venugopal
Venugopal

Reputation: 1

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.])

:)

Upvotes: -1

Ivan Bilan
Ivan Bilan

Reputation: 2439

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

Upvotes: 0

Akavall
Akavall

Reputation: 86306

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.

Upvotes: 0

abarnert
abarnert

Reputation: 366053

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?

Upvotes: 4

Joran Beasley
Joran Beasley

Reputation: 114068

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

:P

Upvotes: 3

Related Questions