从numpy ndarray提取字典项

时间:2019-02-07 11:51:42

标签: 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。

这是怎么回事?

1 个答案:

答案 0 :(得分:2)

您加载的数组实际上是一个scalar,这意味着它是一个具有空形状的数组对象,表示“非数组”值。特别是,数据类型为object的标量包含Python dict,而Python 'trajectories'则在键dt.item()['trajectories'] 下包含一个数字NumPy数组。

在许多情况下,可以不明显地使用NumPy标量与其包含的值(例如,可以像常规Python数字一样非常使用标量数字)。但是,使用对象会更加复杂,因为对象的方法不会通过NumPy标量公开。要“解压缩”标量,可以使用item方法,该方法将获取“裸露”内部值。然后,您将能够照常使用该对象。例如,就您而言,您可以执行以下操作:

def value = messageExchange.responseHeaders["session-id"];
assert value != null
assert value.size() == 1
context.setProperty("sessionID", value)

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