NumPy types with underscore: `int_`, `float_`, etc

自闭症网瘾萝莉.ら 提交于 2021-02-07 05:01:13

问题


What is the significance of the underscore suffixing in int_, float_, etc.?


回答1:


From page 21 of Guide to Numpy by TE Oliphant:

Names for the data types that would clash with standard Python object names are followed by a trailing underscore, ’ ’. These data types are so named because they use the same underlying precision as the corresponding Python data types.

. . .

The array types bool_, int_, complex_, float_, object_, unicode_, and str_ are enhanced-scalars. They are very similar to the standard Python types (without the trailing underscore) and inherit from them (except for bool_ and object_). They can be used in place of the standard Python types whenever desired. Whenever a data type is required, as an argument, the standard Python types are recognized as well.




回答2:


If you're unsure if your variable is scalar, list, or array, using the ones with "_" will ensure your code will work regardless (if that's the behavior you intended). See the example code below.

import numpy as np
scalar = 3
L1 = [3]
L2 = [1, 2, 3]

np.float(scalar)  # okay
np.float(L1)  # breaks (TypeError)
np.float(L2)  # breaks (TypeError)

np.float_(scalar)  # okay
np.float_(L1)  # okay
np.float_(L2)  # okay


来源:https://stackoverflow.com/questions/6205020/numpy-types-with-underscore-int-float-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!