【问题标题】:numpy typing: specifying only some dimensions of the array?numpy打字:只指定数组的某些维度?
【发布时间】:2022-08-05 03:14:04
【问题描述】:

这是 numpy 类型的文档:

https://numpy.org/doc/stable/reference/typing.html#module-numpy.typing

例如,我想将类型指定为大小为 (any,3) 的数组。

以下:

Trajectory = npt.NDArray[(typing.Any, 3), np.float32]

有 mypy 抱怨:

错误:类型 \"Type[ndarray[Any, Any]]\" 不是通用且不可索引的

我找不到这样做的正确方法。还是不支持?

    标签: python numpy typing


    【解决方案1】:

    您不使用 numpy 类型指定大小,只指定数组的类型:

    Trajectory = npt.NDArray[np.float32]

    创建数组时,您可以像这样使用这种类型(例如):arr: Trajectory = np.array(my_trajectory_list)

    指定形状可以这样完成:

    arr: Trajectory = np.empty(shape=(input_length, 3))

    但是您不能将长度设置为Any

    【讨论】:

      【解决方案2】:

      我没有探索 numpy 类型,但我会使用 int 类型别名来做到这一点:

      NSamples = int
      ThreeFeatures = int  # = 3
      FeaturesArray = np.ndarray[(NSamples, ThreeFeatures), float]
      

      或者只是np.ndarray[(int, int), float],如果你喜欢更少的冗长。

      【讨论】:

        猜你喜欢
        • 2018-10-12
        • 2013-09-16
        • 2018-01-13
        • 2011-03-04
        • 2022-06-03
        • 2017-07-21
        • 2017-09-12
        • 1970-01-01
        • 2015-05-25
        相关资源
        最近更新 更多