How to Create Zero or Ones arrays in numpy | numpy.zeros(), numpy.ones()

Spread the love

While we are working on data science or any other projects. we will get requirement of generation of zero array or one arrays. By using we can do easily with the help of numpy.zeros() an numpy.ones() function.

numpy.zeros() function:

This function helps us to create zeros array with desired dimension.

Syntax: numpy.zeros(shape, dtype=float, order=’C’)
Return a new array of given shape and type, filled with zeros.

Parameters:
shape : int or tuple of ints
Shape of the new array, e.g., (2, 3) or 2.

dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

order : {‘C’, ‘F’}, optional, default: ‘C’
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

Returns:
out : ndarray
Array of zeros with the given shape, dtype, and order.

Example program

#creation of numpy array with zeros import numpy as np #single dimention a= np.zeros(10) print('\n one dimensional array',a) #two dimensional zero array a= np.zeros((2,2)) print('\nprinting two dimensional array',a) #three dimensional zero array a= np.zeros((3,3,3)) print('\nprinting three dimensional array',a)

numpy.ones() function:

This function helps us to create ones array with desired dimension.

Syntax: numpy.ones(shape, dtype=None, order=’C’)
Return a new array of given shape and type, filled with ones.

Parameters:
shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.

dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

order : {‘C’, ‘F’}, optional, default: C
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

Returns:
out : ndarray
Array of ones with the given shape, dtype, and order.

Example program

#creation of numpy array with ones import numpy as np #single dimension a= np.ones(10) print('\n one dimensional array',a) #two dimensional ones array a= np.ones((2,2)) print('\n printing two dimensional array',a) #three dimensional ones array a= np.ones((3,3,3)) print('\n printing three dimensional array',a)
admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *