1

I have a numpy ndarray a = np.ndarray((3,3)) and I want all of the indexes to start at the same value, e.g. 5:

array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

Note: I'm posting this Q&A style because every time I look this up I always find a bunch of random questions about complex slicing, but not a simple example of casting everything at once. Hopefully this will pop up as a more immediate result next time I search this question. But I also hope that others have good ideas I can adopt.

loganjones16
  • 492
  • 4
  • 19

3 Answers3

3

Here are some solid ways:

# Use the function built for this very purpose
>>> a = np.full((3, 3), 5)
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

or

# [:] is shorthand for every index.
>>> a = np.ndarray((3,3))
>>> a[:] = 5
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

or

# multiply a single value over every index (currently all 1s)
>>> a = np.ones((3,3)) * 5   
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

Check out the documentation on indexing for more details and examples of complex indexing/slicing

loganjones16
  • 492
  • 4
  • 19
3

There are several alternatives to achieve this, but I think the point will be to analyze which will give you the most optimal results so:

In[1]: %timeit np.ones((3,3)) * 5
6.82 µs ± 374 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)    
In[2]: %%timeit
       np.ndarray((3,3))
       a[:] = 5
1.96 µs ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In[3]: %timeit np.full((3, 3), 5)
4.13 µs ± 59.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

So, probably the best way to do it is creating the array and assigning the value 5 to all elements, that means to use the second option.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
2

I seem to have another way of doing this, just use a plus operator:

>>> import numpy as np
>>> a = np.zeros((3,3))
>>> a
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> a + 5
array([[ 5.,  5.,  5.],
       [ 5.,  5.,  5.],
       [ 5.,  5.,  5.]])
>>> 

(P.S using zeros instead of ndarray)

U13-Forward
  • 69,221
  • 14
  • 89
  • 114