Richard
Richard

Reputation: 197

Create a numpy array (10x1) with zeros and fives

I'm having trouble figuring out how to create a 10x1 numpy array with the number 5 in the first 3 elements and the other 7 elements with the number 0. Any thoughts on how to do this efficiently?

Upvotes: 1

Views: 7176

Answers (6)

ashish
ashish

Reputation: 1

import numpy as np

array = np.zeros(10)
print("An array of zeros : ")
print (array)

array = np.ones(10)
print("An array of ones : ")
print (array)

array = np.ones(10)*5
print("An array of fives : ")
print (array)

Upvotes: -1

Md Pervez Nawaz
Md Pervez Nawaz

Reputation: 37

import numpy as np
np.repeat([5,0],[3,7]).reshape(10,1)

Upvotes: 0

Forhad Hossain
Forhad Hossain

Reputation: 438

Just do the following.

import numpy as np

arr = np.zeros(10)

arr[:3] = 5

Upvotes: 1

Neil.Corbin
Neil.Corbin

Reputation: 23

Both Alex and ajcr have useful answers but one thing to keep in mind is what your expected data type needs are.

np.zeros for example will cast a float whereas the other two answers will cast an int.

You can of course recast by using the 'astype' method:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html

Upvotes: 0

Alex Riley
Alex Riley

Reputation: 177008

I think the way proposed by Alex Martelli is the clearest but here's another alternative using np.repeat which can be quite useful for constructing arrays with repeating values:

>>> np.repeat([5, 0], [3, 7])
array([5, 5, 5, 0, 0, 0, 0, 0, 0, 0])

So here, a list of values [5, 0] is passed in along with a list of repeats [3, 7]. In the returned NumPy array the first element of the values list, 5, is repeated 3 times and the second element 0 is repeated 7 times.

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 882561

Simplest would seem to be:

import numpy as np

the_array = np.array([5]*3 + [0]*7)

Does this simple approach present some specific disadvantage for your purposes?

Of course there are many alternatives, such as

the_array = np.zeros((10,))
the_array[:3] = 5

If you need to repeat this specific operation a huge number of times, so small differences in speed matter, you could benchmark various approaches to see where a nanosecond or so might be saved. But the premise is so unlikely I would not suggest doing that for this specific question, even though I'm a big fan of timeit:-).

Upvotes: 4

Related Questions