Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a numpy array with the same number? [duplicate]

Tags:

numpy

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?

like image 472
Hanfei Sun Avatar asked Nov 02 '12 08:11

Hanfei Sun


People also ask

How do I create a NumPy array with the same value?

Use numpy. full() to fill an array with all identical values Call numpy. full(shape, fill_value) with shape as an x, y tuple to create an array with x rows, y columns, and each element as fill_value .

How do you make an array of the same value?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

How do you repeat an array in Python?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

How does NP repeat work?

The NumPy repeat function essentially repeats the numbers inside of an array. It repeats the individual elements of an array. Having said that, the behavior of NumPy repeat is a little hard to understand sometimes.


2 Answers

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)
like image 136
seberg Avatar answered Oct 01 '22 00:10

seberg


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.

like image 34
Senthil Babu Avatar answered Sep 30 '22 23:09

Senthil Babu