NumPy | full_like method
full_like(~) method creates a Numpy array from an existing array, and fills it with the desired value. This is similar to the other Numpy
_like methods such as
Source array that will be used to construct the Numpy array. By default, the Numpy array will adopt the data type of the values as well as the size of the source array.
The values to fill the Numpy array.
The desired data type for the Numpy array. By default, the data-type would be the same as that of the source array.
A Numpy array filled with the desired value, with the same shape and type as the source array.
Using Numpy arrays
x = np.array([3,4,5])np.full_like(x, 7)array([7, 7, 7])
Using Python arrays
x = [1,2,3]np.full_like(x, 4)array([4., 4., 4.])
Filling a value with a type different than that of the source array
Suppose you wanted to create a Numpy array using a float, like
2.5. You might run into the following trap:
x = np.array([3,4,5])np.full_like(x, 2.5)array([2, 2, 2])
Even when we specified a
2.5, our Numpy array is filled with an
int of value
2 instead. This happens because the original Numpy array (i.e. x in this case) is of type int, and so automatically, the
full_like method assumes that you want to use
int for your new Numpy array.
The solution is to specify the
dtype parameter, like follows:
x = np.array([3,4,5])np.full_like(x, 2.5, dtype=float)array([2.5, 2.5, 2.5])
x = [1,2,3]np.full_like(x, 4, dtype="float")array([4., 4., 4.])
Notice how the values in the output Numpy array are
4. instead of just
4 - this means that the values are floats.
x = [[1,2], [3,4]]np.full_like(x, 5)array([[5, 5],[5, 5]])