【问题标题】:Where can I find Numpy's astype() function definition?我在哪里可以找到 Numpy 的 astype() 函数定义?
【发布时间】:2018-09-26 10:51:19
【问题描述】:

我偶然发现了这段代码:

np.array([1,2,None]).astype(float)

产生:

array([ 1.,  2., nan])

我想看看这段代码如何将 None 转换为 nan。所以我在 Numpy 的 GitHub 存储库中搜索了 astype 函数定义。你能帮我找到它显示用于将None转换为nan的代码的部分吗?我没有足够的 Python 知识来理解像 Numpy 这样的库是如何做事的。看了他们的代码,感觉自己对python不太了解。

我能从中找到的只是https://github.com/numpy/numpy/blob/464f79eb1d05bf938d16b49da1c39a4e02506fa3/numpy/lib/user_array.py#L240中的这个:

def astype(self, typecode):
        ""
        return self._rc(self.array.astype(typecode))

我不知道 Numpy 是如何使用这个函数的。我在整个存储库中找不到任何其他出现的 astype 函数定义。

【问题讨论】:

  • 它是在 C 中实现的。我认为它在 here 中,但我无法很好地阅读 C 以准确了解正在发生的事情
  • 还有一些here

标签: python numpy


【解决方案1】:

很难跟踪已编译的 numpy 代码的操作。即使您可以找到astype 方法,您也可能需要向下挖掘几层才能看到您想要的。 top 方法可能侧重于解释参数,而转换本身可能发生在完全不同的代码部分中。

请注意,您的数组是object dtype,正是因为那个None 对象。其他元素都是整数,

In [48]: np.array([1,2,None])
Out[48]: array([1, 2, None], dtype=object)

如果我告诉它创建一个int dtype 数组,它会引发错误:

In [49]: np.array([1,2,None],int)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-c65114b3ba97> in <module>()
----> 1 np.array([1,2,None],int)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

这与我使用 int(None) 时遇到的错误相同。

指定float dtype,我会像你一样得到nan。实际上,此 np.array 调用与您的 astype 方法相同。 (明白我的意思是很难确定“转换”在哪里进行了吗?)

In [50]: np.array([1,2,None],float)
Out[50]: array([ 1.,  2., nan])

现在float(None) 引发了类似的错误,因此None 上的numpy 处理与Python 不同。

numpy 还将字符串 'nan' 转换为 float nan

In [56]: np.array([1,2,'nan'],float)
Out[56]: array([ 1.,  2., nan])

None 被转换为浮点数nan 并不奇怪。毕竟,它代表not a number。但是很难在numpy 代码中找到产生该等价的确切位置(或多个位置)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多