python - Python 中的 Numpy 类型提示 (PEP 484)

标签 python numpy pep

我想将类型提示添加到将 numpy 数组作为输入并返回字符串的方法。这个 numpy 数组包含 float ,所以我尝试了:

import numpy as np
def foo(array: np.ndarray[np.float64]) -> str:

但由于 TypeError: 'type' object is not subscriptable 而无法工作。

我找到了 this但无法关注讨论!

最佳答案

查看 nptyping .它为 numpy 数组提供类型提示。

在你的情况下,你最终会得到:

from nptyping import NDArray, Float64

def foo(array: NDArray[Float64]) -> str:
    ...

您也可以检查您的实例:

import numpy as np
from nptyping import NDArray, Float64

arr = np.array([[1.0, 2.0],
                [3.0, 4.0],
                [5.0, 6.0]])

isinstance(arr, NDArray[(3, 2), Float64])  # True.

# Or if you don't want to check the dimensions and their sizes:
isinstance(arr, NDArray[Float64])  # Also True.

关于python - Python 中的 Numpy 类型提示 (PEP 484),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839427/

相关文章:

python - 使用 dtype 读取二进制文件会导致 ValueError

python - 为什么 Pandas 或 numpy 中没有正确的 datetime.time 类型?

python - Python 之禅 'Explicit is better than implicit'

python - 三双引号 vs.双引号

python - 如何找出K-最近邻算法中属性的权重?

python - 如何将 python 脚本 cmd 输出重定向到文件?

python - Web.py 中的子应用总是返回 405

python - 使用 scipy.optimize 动态选择参数以最小化 python 中的函数

python - Pandas :合并数据框和替换值

Python,我需要返回作为参数传入的对象吗?