Using numpy.logical_xor() function (5 examples)

Updated: March 1, 2024 By: Guest Contributor Post a comment

Introduction

The numpy.logical_xor() function presents a powerful tool for those delving into data analysis, signal processing, and beyond, by offering a straightforward way to compute the logical exclusive OR (XOR) operation on arrays. XOR is a binary operation that returns True only when inputs differ (i.e., one is True, and the other is False).

In this tutorial, we’ll explore how to utilize the numpy.logical_xor() function effectively across 5 distinct examples, scaling from basic to advanced use cases. Whether you’re new to NumPy or looking to deepen your array manipulation savvy, this guide aims to enlighten.

Syntax & Parameters

The numpy.logical_xor() function performs element-wise logical exclusive OR (XOR) operation on two arrays, returning True when exactly one of the operands is True. Below’s its syntax:

numpy.logical_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Where:

  • x1, x2: These are the input arrays for which the logical XOR operation is to be computed. The function compares these inputs element-wise and returns True where exactly one of the inputs is True.
  • out: This optional parameter specifies an alternative output array in which to place the result. It must have a shape that the inputs broadcast to. If not provided or None, a newly allocated array is returned.
  • where: This is an optional condition array_like object. The operation is performed only at positions where the condition array is True. This allows for selective computation within the arrays. If not provided, the operation is performed on the entire array.
  • casting: Controls what kind of data casting may occur when performing the operation. Options like 'no', 'equiv', 'safe', 'same_kind', and 'unsafe' dictate how flexible type casting is. This can be important for operations involving arrays of different data types.
  • order: Specifies the memory layout of the output array. 'C' means C-order, 'F' means Fortran-order, 'A' means ‘F’ if an input is Fortran contiguous, ‘C’ otherwise. 'K' means as close to the order the array elements appear in memory as possible.
  • dtype: An optional parameter specifying the desired data-type for the output array. The computation and the output will be cast to this dtype if provided.
  • subok: If set to True, subclasses are preserved during the operation. This is useful if you are working with arrays that are instances of subclasses of ndarray.
  • signature, extobj: These are advanced options rarely used in typical applications. signature allows for defining a generalized ufunc signature for more advanced control over broadcasting and output shapes. extobj provides a way to control certain aspects of ufunc behavior, like buffering and error handling, but is generally not used in day-to-day operations.

Example 1: Basic Usage

Let’s kick things off with the fundamentals. The simplest form of utilizing numpy.logical_xor() is by passing two boolean values:

import numpy as np

result = np.logical_xor(True, False)
print(result)  
# Output: True

Example 2: Array Inputs

import numpy as np

a = np.array([True, False, True, False])
b = np.array([True, True, False, False])
result = np.logical_xor(a, b)
print(result)  
# Output: array([False,  True,  True, False])

Example 3: Mixing Data Types

This example demonstrates the function’s flexibility by applying it to an array of boolean values and integers. This capability makes numpy.logical_xor() exceptionally versatile:

import numpy as np

a = np.array([1, 0, 1, 0])
b = np.array([True, True, False, False])
result = np.logical_xor(a, b)
print(result)  
# Output: array([False,  True,  True, False])

Example 4: Applying on 2D Arrays

The versatility of numpy.logical_xor() extends to multidimensional arrays, adding depth to its applications. Here’s how it works for 2D arrays:

import numpy as np

a = np.array([[True, False], [True, False]])
b = np.array([[True, True], [False, False]])
result = np.logical_xor(a, b)
print(result)  
# Output: array([[False,  True],
                 [ True, False]])

Example 5: Real-world Application – Filtering Data

For our final example, let’s dive into a real-world application. Suppose you’re analyzing survey data and want to filter out respondents based on two criteria, achieving this efficiently with numpy.logical_xor():

import numpy as np

# Suppose these arrays represent two criteria:
# 'a' for respondents who completed a survey on mobile,
# 'b' for those who rated the service over 3 stars.
a = np.array([True, False, True, False, True])
b = np.array([True, True, False, False, True])

# Applying logical_xor to find respondents who fulfilled exactly one criterion.
filtered = np.logical_xor(a, b)
print(filtered)  
# Output: array([False,  True,  True, False, False])

Conclusion

The numpy.logical_xor() function stands as a testament to the elegance and simplicity of Boolean operations in array manipulation. Through our exploration from basic examples to a real-world application, it’s clear this function holds significant utility across various domains. Let’s harness its power to enrich our data analysis and signal processing endeavors.