从 numpy ndarray 中提取字典项
Extract dictionary item from 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 对象对我来说就像一本字典。但是,当我尝试索引 'trajectories' 时,我收到错误消息:
>>>>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,这意味着它是一个空形状的数组对象,代表一个 "non-array" 值。特别是,是一个数据类型为 object
的标量,其中包含一个 Python dict
,它又包含一个位于键 'trajectories'
.
下的数字 NumPy 数组
在许多情况下,NumPy 标量的使用方式与它们包含的值不同(例如,标量数字的使用方式与常规 Python 数字非常相似)。然而,对于对象来说,情况要复杂得多,因为对象的方法不会通过 NumPy 标量公开。对于 "unpack" 标量,您可以使用 item
方法,该方法将获得 "bare" 内部值。然后您将能够像往常一样使用该对象。例如,在你的情况下,你可以这样做:
dt.item()['trajectories']
这将为您提供字典中的内部数组。
我正在 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 对象对我来说就像一本字典。但是,当我尝试索引 'trajectories' 时,我收到错误消息:
>>>>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,这意味着它是一个空形状的数组对象,代表一个 "non-array" 值。特别是,是一个数据类型为 object
的标量,其中包含一个 Python dict
,它又包含一个位于键 'trajectories'
.
在许多情况下,NumPy 标量的使用方式与它们包含的值不同(例如,标量数字的使用方式与常规 Python 数字非常相似)。然而,对于对象来说,情况要复杂得多,因为对象的方法不会通过 NumPy 标量公开。对于 "unpack" 标量,您可以使用 item
方法,该方法将获得 "bare" 内部值。然后您将能够像往常一样使用该对象。例如,在你的情况下,你可以这样做:
dt.item()['trajectories']
这将为您提供字典中的内部数组。