简体   繁体   English

如何在Python中使用isinstance检查float?

[英]How to check float using isinstance in Python?

I cannot make sense of below: When I check the type of "RUN_ID", it clearly states "float". 我无法理解以下内容:当我检查“ RUN_ID”的类型时,它会清楚地注明“ float”。 But when I check if it is float, it returns False. 但是当我检查它是否为float时,它返回False。 What is this type exactly and how to check? 到底是什么类型?如何检查?

tags.loc[0, 'RUN_ID']
Out[36]: 38607.0   
type(tags.loc[0, 'RUN_ID'])
Out[34]: float 
isinstance(type(tags.loc[0, 'RUN_ID']),np.float64)
Out[32]: False
isinstance(type(tags.loc[0, 'RUN_ID']),np.float32)
Out[33]: False

isinstance(type(tags.loc[0, 'RUN_ID']),float)
Out[35]: False

You're using isinstance wrong. 您使用的isinstance错误。 Instead of 代替

isinstance(type(tags.loc[0, 'RUN_ID']),float)

just do 做就是了

isinstance(tags.loc[0, 'RUN_ID'],float)

The type() function returns an object of type type , where you want the type of the object itself. type()函数返回类型为type的对象,您需要该对象本身的类型。

isinstance(type(tags.loc[0, 'RUN_ID']),float) 

returns false because type(tags.loc[0, 'RUN_ID']) returns float , which is actually of type type . 返回false,因为type(tags.loc[0, 'RUN_ID'])返回float ,实际上是type type You can verify that by saying something like 您可以说出类似

type(type(tags.loc[0, RUN_ID'])) 

So you're actually checking to see if the type of the type float is the same as the type float , which is False . 所以你实际上检查,看看是否该类型的类型float是相同类型的float ,这是False

So maybe try 所以也许尝试

isinstance(tags.loc[0, 'RUN_ID'],float)?

check with the regular float type instead of numpy. 检查常规浮点类型而不是numpy。 Test results below 测试结果如下

w = isinstance(n, float)    # True
x = isinstance(n, np.float32)   # False
y = isinstance(n, np.float64)   # False
z = type(n) == float        # True

I believe isinstance() checks more if a value is a certain class rather than if two class values are the same. 我相信isinstance()会检查更多值,如果某个值是某个类,而不是两个类值是否相同。

For example, isinstance(0.35, float) returns True. 例如, isinstance(0.35, float)返回True。

The way you have it is basically asking "Is the type float an instance of a float?" 您拥有的方式基本上是在询问“类型float是否是float的实例?” which is not correct. 这是不正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM