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?

talonmies
  • 70,661
  • 34
  • 192
  • 269
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

4 Answers4

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)
Mike T
  • 41,085
  • 18
  • 152
  • 203
seberg
  • 8,785
  • 2
  • 31
  • 30
  • Or `a[:] = 9`. This is more idiomatic, to me at least. – mtrw Nov 02 '12 at 14:21
  • 3
    @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. – seberg Nov 02 '12 at 14:56
  • interesting, I hadn't thought about the singleton issue. Thanks! – mtrw Nov 02 '12 at 15:00
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.

Senthil Babu
  • 1,243
  • 2
  • 11
  • 20
  • 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. – Mark Nov 07 '16 at 10:57
1

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

Community
  • 1
  • 1
Rolf Bartstra
  • 1,643
  • 1
  • 16
  • 19
-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.

bidifx
  • 1,640
  • 13
  • 19