Return a new array of given shape filled with ones but with different datatype in Numpy

NumpyServer Side ProgrammingProgramming

To return a new array of given shape and type, filled with ones, use the numpy.ones() method in Python Numpy. The 1st parameter sets the number of rows. The 2nd parameter sets the number of columns. Both 1st and 2nd parameters forms the shape of the array. The "dtype" parameter is used to set the desired data-type for the array.

The function returns an array of ones with the given shape, dtype, and order. The order suggests wether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) 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 ones, use the numpy.ones() method in Python Numpy. The "dtype" parameter is used to set the desired data-type for the array −

arr = np.ones((4,5), dtype = int)

Display the 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 in 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 ones, use the numpy.ones() method in Python Numpy
# The 1st parameter sets the number of rows
# The 2nd parameter sets the number of columns
# Both 1st and 2nd parameters forms the shape of the array
# The "dtype" parameter is used to set the desired data-type for the array
arr = np.ones((4,5), dtype = int)

# 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...
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(4, 5)

Elements in the Array...
20
raja
Updated on 10-Feb-2022 06:59:12

Advertisements