gpt4 book ai didi

Python 检查数组的 dtype - float 或 complex

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:18 24 4
gpt4 key购买 nike

如果 numpy 数组是 float 或 complex dtype,我该如何检查?对于简单示例,以下检查一切正常。

# these are True
a = np.zeros(10)
a.dtype == float
a.dtype == np.float
a.dtype == np.float64

b = np.zeros(10,dtype=complex)
b.dtype == complex
b.dtype == np.complex
b.dtype == np.complex128

但是,我有一个 dtype 数组 dtype('>f8')。之前的比较都没有将其识别为 float 组。据我所知,字节顺序(> 与 <)是那里的问题。是否有任何通用函数来检查数组是 float 还是具有所有变化的复数?

最佳答案

您是否尝试过 numpy.isrealobj()np.iscomplexobj()

你的例子:

import numpy as np

a = np.zeros(10)
print(np.isrealobj(a)) # -> True
print(np.iscomplexobj(a)) # -> False

b = np.zeros(10,dtype=complex)
print(np.isrealobj(b)) # -> False
print(np.iscomplexobj(b)) # -> True

c=np.zeros(10, dtype='>f8')
print(np.isrealobj(c)) # -> True
print(np.iscomplexobj(c)) # -> False

np.isrealobj(x) 的文档说明:

Return True if x is a not complex type or an array of complex numbers.

The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, isrealobj evaluates to False if the data type is complex.

也可以按值检查:np.isrealnp.iscomplex

这有帮助吗?

关于Python 检查数组的 dtype - float 或 complex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56936068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com