w3resource

NumPy: Create an array of ones and an array of zeros


Create Zeros and Ones Array

Write a NumPy program to create an array of ones and zeros.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Printing a message about creating an array of zeros
print("Create an array of zeros")

# Creating a 1x2 array filled with zeros, default type is float
x = np.zeros((1,2))
# Printing the default type (float) of the created array
print("Default type is float")
# Displaying the created array of zeros
print(x)

# Changing the type of the array 'x' to integer
print("Type changes to int")
x = np.zeros((1,2), dtype=np.int)
# Displaying the array 'x' after changing its type to integer
print(x)

# Printing a message about creating an array of ones
print("Create an array of ones")

# Creating a 1x2 array filled with ones, default type is float
y = np.ones((1,2))
# Printing the default type (float) of the created array
print("Default type is float")
# Displaying the created array of ones
print(y)

# Changing the type of the array 'y' to integer
print("Type changes to int")
y = np.ones((1,2), dtype=np.int)
# Displaying the array 'y' after changing its type to integer
print(y)

Sample Output:

Create an array of zeros                                               
Default type is float                                                  
[[ 0.  0.]]                                                            
Type changes to int                                                    
[[0 0]]                                                                
Create an array of ones                                                
Default type is float                                                  
[[ 1.  1.]]                                                            
Type changes to int                                                    
[[1 1]]

Explanation:

In the above code -

x = np.zeros((1,2)): This line creates a NumPy array ‘x’ of shape (1, 2) filled with zeros. By default, the dtype is 'float64'.

x = np.zeros((1,2), dtype = np.int): This line reassigns ‘x’ to a new array with the same shape (1, 2) filled with zeros, but with the dtype set to 'int' (integer).

print(x): This line prints the integer array x filled with zeros.

y = np.ones((1,2)): This line creates a NumPy array ‘y’ of shape (1, 2) filled with ones. By default, the dtype is 'float64'.

y = np.ones((1,2), dtype = np.int): This line reassigns ‘y’ to a new array with the same shape (1, 2) filled with ones, but with the dtype set to 'int' (integer).

print(y): This line prints the integer array ‘y’ filled with ones.

Python-Numpy Code Editor: