NumPy logical_or function

Overview:

  • The numpy.logical_or() function applies logical OR between the elements of two numpy array-like instances. The logical OR operation returns True when one of the operands is True, else it returns False.

  • The numpy.bitwise_or() function is applied between the binary bits of the elements of two NumPy array-likes.

Truth table - OR operation:

Operand 1 Operand 2 Operand 1 OR Operand 2
0 0 0
0 1 1
1 0 1
1 1 1

Example 1:

# Example Python program that applies 
# numpy.logical_or() function between
# the elements of two NumPy array-likes
import numpy
from random import randrange

# Populate ndarray with random zeros and ones
def populateNDArray(array_in):
    for x in range(0, 3):
        for y in range(0, 3):
            array_in[x][y] = randrange(2)

# Creation of ndarrays
boolArray1 = numpy.ndarray(shape = (3, 3), dtype = numpy.int32)
boolArray2 = numpy.ndarray(shape = (3, 3), dtype = numpy.int32)

populateNDArray(boolArray1)
populateNDArray(boolArray2)

# Apply logical OR between array elements
orResults = numpy.logical_or(boolArray1, boolArray2)

print("Boolean array1:")
print(boolArray1)
print("Boolean array2:")
print(boolArray2)
print("Array1 or array2:")
print(orResults)

Output:

Boolean array1:

[[0 0 0]

 [1 1 0]

 [1 1 0]]

Boolean array2:

[[1 0 1]

 [1 1 0]

 [1 0 1]]

Array1 or array2:

[[ True False  True]

 [ True  True False]

 [ True  True  True]]

Example 2:

# Example Python program that does
# (Python List 1 OR Python List 2)
# and returns the results as an ndarray
import numpy

# The Python list is converted to ndarray internally
flags1 = [1, 1, 0, 0, 0]
flags2 = [1, 0, 1, 0, 1]

# Apply logical OR
orResults = numpy.logical_or(flags1, flags2)

# Print operands
print(type(flags1))
print(flags1)

print(type(flags2))
print(flags2)

# Print results
print(type(orResults))
print(orResults)

Output:

<class 'list'>

[1, 1, 0, 0, 0]

<class 'list'>

[1, 0, 1, 0, 1]

<class 'numpy.ndarray'>

[ True  True  True False  True]

 


Copyright 2024 © pythontic.com