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


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 shape of the new array.

The function returns an array of ones with the given shape, dtype, and order. The dtype parameter is the desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. 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 1st parameter sets the shape of the new array −

arr = np.ones((4))

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements in the Array −

print("
Elements in the Array...
",arr.size)

Example

import numpy as np
import numpy.ma as ma

# 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 shape of the new array
arr = np.ones((4))

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)

Output

Array...
[1. 1. 1. 1.]

Array datatype...
float64

Array Dimensions...
1

Our Array Shape...
(4,)

Elements in the Array...
4

Updated on: 10-Feb-2022

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements