python - 从 numpy ndarray 中提取字典项

标签 python numpy numpy-ndarray

我正在 Python 3.7 中加载一个 .npy 文件。输出如下所示:

>>>import numpy as np
>>>dt = np.load('trajectories.npy')
>>>dt
array({'trajectories': array([[[729.78449821, 391.1702509],
[912.41666667, 315.5       ],
[832.0577381 , 325.83452381]],
...,
[[852.92      , 174.16253968],
[923.36053131, 347.92694497],
[878.89942529, 323.26652299]]]), video_path: 'myPath', frames_per_second: 28}, dtype = object)

鉴于我是 numpy ndarrays 的新手,dt 对象对我来说就像一本字典。但是,当我尝试为“轨迹”编制索引时,我收到错误消息:

>>>>dt['trajectories']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
>>>>dt.get('trajectories')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'get'

当我把它当作一个数组时:

>>>dt[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array

当我尝试将数组转换为元组时,我被告知数组是 0-d。

这是怎么回事?

最佳答案

你加载的数组实际上是一个scalar ,这意味着它是一个具有空形状的数组对象,表示“非数组”值。特别是,是一个数据类型为 object 的标量,其中包含一个 Python dict,它又包含一个位于键 'trajectories' 下的数字 NumPy 数组.

在许多情况下,NumPy 标量的使用方式与它们包含的值没有区别(例如,标量数字的使用方式与常规 Python 数字非常相似)。然而,对于对象来说,情况要复杂得多,因为对象的方法不会通过 NumPy 标量公开。要“解压缩”标量,您可以使用 item方法,它将获得“裸”内在值(value)。然后您将能够像往常一样使用该对象。例如,在您的情况下,您可以这样做:

dt.item()['trajectories']

这将为您提供字典中的内部数组。

关于python - 从 numpy ndarray 中提取字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572753/

相关文章:

python - lxml 在解析之前不会将 int 强制转换为字符串

python - 将边界框区域转换为 mask 并将其另存为PNG文件

python - 瞄准质心 - scipy/numpy

python-3.x - 在 pyqtgraph.ImageView() 上绘制线条

python - python中3D numpy数组的体积计算?

python - 尝试使用 BigQuery 获取 PyPI 的下载统计信息时出现无法找到数据集错误

python - 我的函数对是否需要第二个参数感到困惑(python,matplotlib)

python - 查找列之间不匹配的条目并遍历列

python - 有条件地删除重复项 pandas python

python - 基于 bool np.array 有效地对 np.matrix 进行子集化,但仅直到某个阈值