How do I create an array whose elements are all equal to a specified value?

numpy, python, scipy

Solution

I don't know if there's a nice one-liner without an arithmetic operation, but probably the fastest approach is to create an uninitialized array using `empty` and then use `.fill()` to set the values. For comparison:

>>> timeit m = np.zeros((3,3)); m += -1
100000 loops, best of 3: 6.9 us per loop
>>> timeit m = np.ones((3,3)); m *= -1
100000 loops, best of 3: 9.49 us per loop
>>> timeit m = np.zeros((3,3)); m.fill(-1)
100000 loops, best of 3: 2.31 us per loop
>>> timeit m = np.empty((3,3)); m[:] = -1
100000 loops, best of 3: 3.18 us per loop

>>> timeit m = np.empty((3,3)); m.fill(-1)
100000 loops, best of 3: 2.09 us per loop

but to be honest, I tend to either add to the zero matrix or multiply the ones matrix instead, as initialization is seldom a bottleneck.

Problem

How do I create an array where every entry is the same value? I know `numpy.ones()` and `numpy.zeros()` do this for 1's and 0's, but what about `-1`? For example: ``` >>import numpy as np >>np.zeros((3,3)) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) >>np.ones((2,5)) array([[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]]) >>np.negative_ones((2,5)) ??? ```

Original source