How to create in one line a zero vector of size 10, but the fifth value is 1 using numpy

I can do this in two lines for the numpy module:

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

However, I was wondering if it is possible to combine them together.

+4
source share
5 answers

There are several ways to do this. For example, np.arange(10) == 4it gives you an array of all values Falseexcept one Trueat position 4.

Under the covers, NumPy values boolare equal 0and 1how uint8(just like Python values bool 0and 1, although they have a unique integral type) so you can just use it as it 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])

... view uint8 bool:

>>> (np.arange(10) == 4).view(np.uint8)
array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=uint8)

... , int, :

>>> (np.arange(10) == 4).astype(int)

array ([0, 0, 0, 0, 1, 0, 0, 0, 0, 0])

.

, , 20% , , , , ?

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

:

+2

, :

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

.

:

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

, x 1 - , python . x element 4 1.

, element 4 1, .

0

:

my_vect = np.zeros(42)
# set index 1 and 3 to value 1
my_vect[np.array([1,3])] = 1
0
source
array = numpy.eye( array_size )[ element_in_array_which_should_be_1 - 1 ]

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

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

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

:)

-1
source

All Articles