w3resource

NumPy: Test whether a given 2D array has null columns or not

NumPy: Array Object Exercise-183 with Solution

Write a NumPy program to test whether a given 2D array has null columns or not.

Pictorial Presentation:

Python NumPy: Test whether a given 2D array has null columns or not

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Displaying the message indicating the original array
print("Original array:")

# Generating a random integer array of shape (4, 10) with values ranging from 0 to 2
nums = np.random.randint(0, 3, (4, 10))

# Displaying the original array
print(nums)

# Checking if the array has any null columns and displaying the result
print("\nTest whether the said array has null columns or not:")
print((~nums.any(axis=0)).any()) 

Sample Output:

Original array:
[[1 2 1 1 1 2 1 1 2 0]
 [1 1 0 0 0 0 2 1 2 0]
 [0 0 2 1 0 2 2 2 2 2]
 [1 1 1 2 0 0 0 0 1 2]]

Test whether the said array has null columns or not:
False

Explanation:

In the above exercise -

nums = np.random.randint(0,3,(4,10)): Generates a 4x10 NumPy array nums with random integers from the range [0, 3).

print((~nums.any(axis=0)).any()):

In the above code -

  • nums.any(axis=0): Returns a boolean array of shape (10,) with True at positions where there is at least one non-zero element in the corresponding column of nums, and False otherwise. The axis=0 parameter specifies that the operation should be performed along the columns.
  • ~nums.any(axis=0): Inverts the boolean values in the array from step 2 using the bitwise NOT operator ~. Now, True indicates that a column has all zeros, and False indicates that there is at least one non-zero element in the column.
  • (~nums.any(axis=0)).any(): Checks if there is at least one True value in the boolean array from step 3, i.e., if there is any column in nums with all zeros.
  • print((~nums.any(axis=0)).any()): Finally print() function prints the result from step 4. If it prints True, there is at least one column with all zeros; otherwise, no such column exists.

Python-Numpy Code Editor:

Previous: Write a NumPy program to subtract the mean of each row of a given matrix.
Next: Write a NumPy program to create an array using generator function that generates 15 integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-183.php