基于NumPy条件,计算数组与另一个数组按元素进行异或运算后的真值
要计算数组与另一个数组按元素进行异或运算后的真值,请在 Python NumPy 中使用 **numpy.logical_xor()** 方法。返回值为 True 或 False。这里我们设置了条件。返回值是应用于 x1 和 x2 元素的逻辑异或运算的布尔结果;形状由广播确定。如果 x1 和 x2 都是标量,则这是一个标量。
条件会在输入上进行广播。在条件为 True 的位置,输出数组将设置为 ufunc 结果。在其他位置,输出数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的输出数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建两个 2D NumPy 数组。我们插入了元素。True 被认为是值 1,False 被认为是值 0:
arr1 = np.array([[True, 8, 7], [13, False, 11]]) arr2 = np.array([[False, 9, True], [19, 25, 6]])
显示数组:
print("Array 1...
", arr1)
print("
Array 2...
", arr2)获取数组的类型:
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)获取数组的维度:
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)获取数组的形状:
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)要计算数组与另一个数组按元素进行异或运算后的真值,请使用 numpy.logical_xor() 方法。返回值为 True 或 False。这里我们设置了条件:
print("
Result (XOR)...
",np.logical_xor(arr1 > 10, arr2 < 15))示例
import numpy as np
import numpy.ma as ma
# Creating two 2D numpy array using the array() method
# We have inserted elements
# The True is considered value 1
# The False is considered value 0
arr1 = np.array([[True, 8, 7], [13, False, 11]])
arr2 = np.array([[False, 9, True], [19, 25, 6]])
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Get the shape of the Arrays
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)
# To compute the truth value of an array XOR another array elementwise, use the numpy.logical_xor() method in Python Numpy
# Return value is either True or False
# We have set conditions here
print("
Result (XOR)...
",np.logical_xor(arr1 > 10, arr2 < 15))输出
Array 1... [[ 1 8 7] [13 0 11]] Array 2... [[ 0 9 1] [19 25 6]] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 3) Our Array 2 Shape... (2, 3) Result (XOR)... [[ True True True] [ True False False]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP