【问题标题】:numpy.asarray: how to check up that its result dtype is numeric?numpy.asarray:如何检查其结果 dtype 是否为数字?
【发布时间】:2015-06-13 15:55:15
【问题描述】:

我必须从具有 int、float 或复数的类似数组的数据中创建 numpy.ndarray

我希望用numpy.asarray函数来做。

我不想给它一个严格的dtype 参数,因为我想将复杂值转换为complex64complex128,浮动为float32float64 等。

但如果我只是简单地运行 numpy.ndarray(some_unknown_data) 并查看其结果的 dtype,我怎么能理解数据是数字,而不是对象或字符串或其他东西?

【问题讨论】:

    标签: python arrays numpy types


    【解决方案1】:

    您可以检查数组的 dtype 是否是 np.number 的子 dtype。例如:

    >>> np.issubdtype(np.complex128, np.number)
    True
    >>> np.issubdtype(np.int32, np.number)
    True
    >>> np.issubdtype(np.str_, np.number)
    False
    >>> np.issubdtype('O', np.number) # 'O' is object
    False
    

    本质上,这只是检查 dtype 是否低于 NumPy dtype hierarchy 中的“数字”:

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 2017-08-18
      • 2020-04-09
      • 2013-05-09
      • 2014-04-13
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多