Combine Boolean arrays using np.logical_and in NumPy
NumPy: Universal Functions Exercise-19 with Solution
ufunc with Boolean Arrays:
Write a NumPy program that uses np.logical_and to combine two boolean arrays based on element-wise logical AND operation.
Sample Solution:
Python Code:
import numpy as np
# Create two boolean arrays
array_a = np.array([True, False, True, False])
array_b = np.array([True, True, False, False])
# Combine the boolean arrays using np.logical_and
result_array = np.logical_and(array_a, array_b)
# Print the original boolean arrays and the result array
print("Array A:")
print(array_a)
print("\nArray B:")
print(array_b)
print("\nResult Array after applying np.logical_and:")
print(result_array)
Output:
Original Complex Array: [1.+2.j 3.+4.j 5.+6.j] Result Array after applying custom ufunc: [3.0 7.0 11.0] runfile('C:/Users/ME/untitled1.py', wdir='C:/Users/ME') Array A: [ True False True False] Array B: [ True True False False] Result Array after applying np.logical_and: [ True False False False]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Create Boolean Arrays:
- Define two boolean arrays 'array_a' and 'array_b' with example data.
- Combine Arrays Using np.logical_and:
- Use "np.logical_and()" to perform an element-wise logical AND operation on the two boolean arrays, storing the result in 'result_array'.
- Print Arrays:
- Output the original boolean arrays and the resulting array after applying "np.logical_and" to verify the operation.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics