Return a new array of given shape filled with a fill value and a different output type in Numpy

NumpyServer Side ProgrammingProgramming

To return a new array of given shape and type, filled with a fill value, use the numpy.full() method in Python Numpy. The 1st parameter is the shape of the new array. The 2nd parameter sets the fill value. The 3rd parameter is used to set the desired data-type of the returned output array.

The dtype is the desired data-type for the array. The order suggests whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

Steps

At first, import the required library −

import numpy as np

To return a new array of given shape and type, filled with a fill value, use the numpy.full() method. The 3rd parameter is used to set the desired data-type of the returned output array −

arr = np.full((4,5), fill_value = 999, dtype = float)

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

Example

import numpy as np

# To return a new array of given shape and type, filled with a fill value, use the numpy.full() method in Python Numpy
# The 1st parameter is the shape of the new array
# The 2nd parameter sets the fill value
# The 3rd parameter is used to set the desired data-type of the returned output array
arr = np.full((4,5), fill_value = 999, dtype = float)

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arr.size)

Output

Array...
[[999. 999. 999. 999. 999.]
[999. 999. 999. 999. 999.]
[999. 999. 999. 999. 999.]
[999. 999. 999. 999. 999.]]

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 5)

Elements in the Array...
20
raja
Updated on 10-Feb-2022 07:39:39

Advertisements