14

I know how to fill with zero in a 100-elements array:

np.zeros(100)

But what if I want to fill it with 9?

0

4 Answers 4

23

You can use:

a = np.empty(100)
a.fill(9)

or also if you prefer the slicing syntax:

a[...] = 9

np.empty is the same as np.ones, etc. but can be a bit faster since it doesn't initialize the data.

In newer numpy versions (1.8 or later), you also have:

np.full(100, 9)
Sign up to request clarification or add additional context in comments.

3 Comments

Or a[:] = 9. This is more idiomatic, to me at least.
@mtrw matter of taste, I like Ellipsis since it says explicitly take everything. Also for the corner case of a singleton array it can mean along no axes: np.array(5)[...] = 8 works, np.array(5)[:] = 8 does not.
interesting, I hadn't thought about the singleton issue. Thanks!
2

If you just want same value throughout the array and you never want to change it, you could trick the stride by making it zero. By this way, you would just take memory for a single value. But you would get a virtual numpy array of any size and shape.

>>> import numpy as np
>>> from numpy.lib import stride_tricks
>>> arr = np.array([10])
>>> stride_tricks.as_strided(arr, (10, ), (0, ))
array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10])

But, note that if you modify any one of the elements, all the values in the array would get modified.

1 Comment

Interesting trick. Though you could probably just use a scalar value instead of an array if it's all the same values that are never going to change.
1

This question has been discussed in some length earlier, see NumPy array initialization (fill with identical values) , also for which method is fastest.

Comments

-1

As far as I can see there is no dedicated function to fill an array with 9s. So you should create an empty (ie uninitialized) array using np.empty(100) and fill it with 9s or whatever in a loop.

2 Comments

yes, but no loop. Use array.fill(9) or array[...] = 9.
@seberg: Your comment should be an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.