In this article we will discuss how to create a Numpy array of different shapes and initialized with 0 & 1.

numpy.zeros()

Python’s Numpy module provides a function to create a numpy array of given shape & type and all values in it initialized with 0’s i.e.

Arguments:

  • shape : Shape of the numpy array. Single int or sequence of int.
  • dtype : (Optional) Data type of elements. Default is float64.
  • order : (Optional) Order in which data is stored in multi-dimension array i.e. in row major(‘F’) or column major (‘C’). Default is ‘C’.

Let’s see some examples,

Create a flattened numpy array filled with all zeros

Output:

Here, in shape argument we passed 5. So, it returned a flattened numpy array of 5 zeros.

Create a 2D numpy array with 5 rows & 6 columns, filled with 0’s

Output:

Here we passed (5,6) as shape argument in numpy.zeros(), therefore it returned a 2D numpy array of 5 rows & 6 column with all zeros.
As default type was float64. Let’s see how to pass the data type int64 i.e.

Output:

It will create a 2D numpy array of ints filled with zeros.

numpy.ones()

Python’s Numpy module provides a function to create a numpy array of given shape & type and all values in it initialized with 1’s i.e.

Arguments:

  • shape : Shape of the numpy array. Single int or sequence of int.
  • dtype : (Optional) Data type of elements. Default is float64.
  • order : (Optional) Order in which data is stored in multi-dimension array i.e. in row major(‘F’) or column major (‘C’). Default is ‘C’.

Let’s see some examples,

Create a flattened numpy array filled with all Ones

Output:

Here, in shape argument we passed 5. So, it returned a flattened numpy array of 5 zeros.

Create a 2D numpy array with 3 rows & 4 columns, filled with 1’s

Output:

Here we passed (3,4) as shape argument in numpy.ones(), therefore it returned a 2D numpy array of 3 rows & 4 column with all zeros.
As default type was float64. Let’s see how to pass the data type int64 i.e.

Output:

It will create a 2D numpy array of ints filled with ones.

Complete example is as follows,

Output

 

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.