How to count number of zeros in NumPy array

You can count the number of zeros in the NumPy array with any of the following methods. If you want to learn Python, I highly recommend reading This Book.

Method 1:

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, 0, 8, 0, 5],
              [0, 5, 2, 3, 0]])

# Count number of zeros
b = np.count_nonzero(a==0)

# Display the Number of Zeros
print(b)

Output:

4

Method 2

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, 0, 8, 0, 5],
              [0, 5, 2, 3, 0]])

# Count number of zeros
b = a[np.where(a == 0)].size

# Display the Number of Zeros
print(b)

Output:

4

Method 3

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, 0, 8, 0, 5],
              [0, 5, 2, 3, 0]])

# Count number of zeros
b = str(a).count('0')

# Display the Number of Zeros
print(b)

Output:

4

How to count the number of zeros in each row?

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, 0, 8, 0, 5],
              [0, 5, 2, 3, 0],
              [7, 0, 1, 8, 9],
              [6, 0, 0, 0, 5]])

# Count number of zeros in each row
b = np.count_nonzero(a==0, axis=1)

# Display the Number of Zeros
print(b)

Output:

[2 2 1 3]

How to count the number of zeros in each column?

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, 0, 8, 0, 5],
              [0, 5, 2, 3, 0],
              [7, 0, 1, 8, 9],
              [6, 0, 0, 0, 5]])

# Count number of zeros in each column
b = np.count_nonzero(a==0, axis=0)

# Display the Number of Zeros
print(b)

Output:

[1 3 1 2 1]

Free Learning Resources

Leave a Comment

Your email address will not be published.