在 NumPy 中计算数组的按元素非运算的真值


要计算数组的按元素非运算的真值,请在 Python NumPy 中使用 **numpy.logical_not()** 方法。返回值为 True 或 False。

返回值是布尔结果,其形状与 x 相同,表示对 x 的元素进行非运算的结果。如果 x 是标量,则这是一个标量。out 是存储结果的位置。如果提供,则其形状必须是输入广播到的形状。如果未提供或为 None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且与分布式、GPU 和稀疏数组库配合良好。

步骤

首先,导入所需的库 -

import numpy as np

使用 array() 方法创建一个二维 NumPy 数组。我们插入了元素 -

arr = np.array([[True, False, True], [True, True, False]])

显示数组 -

print("Array...
", arr)

获取数组的类型 -

print("
Our Array type...
", arr.dtype)

获取数组的维度 -

print("
Our Array Dimension...
",arr.ndim)

获取数组的形状 -

print("
Our Array Shape...
",arr.shape)

要计算数组的按元素非运算的真值,请在 Python NumPy 中使用 numpy.logical_not() 方法。返回值为 True 或 False -

print("
Result (NOT)...
",np.logical_not(arr))

示例

import numpy as np

# Creating a 2D numpy array using the array() method
# We have inserted elements
arr = np.array([[True, False, True], [True, True, False]])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimension of the array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the array print("
Our Array Shape...
",arr.shape) # To compute the truth value of NOT an array element-wise, use the numpy.logical_not() method in Python Numpy # Return value is either True or False print("
Result (NOT)...
",np.logical_not(arr))

输出

Array...
[[ True False True]
[ True True False]]

Our Array type...
bool

Our Array Dimension...
2

Our Array Shape...
(2, 3)

Result (NOT)...
[[False True False]
[False False True]]

更新于: 2022年2月5日

285 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.