获取数组中字典值的向量,python

Getting a vector of dictionary values in an array, python

我正在尝试获取 numpy 数组中特定字典值的向量。这是数组的样子:

import numpy as np
edge_array = np.array(
    [[1001, 7005, {'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}],
     [1001, 8259, {'lanes': 10, 'length': 0.46, 'type': '99', 'modes': 'cw'}],
     [1001, 14007, {'lanes': 7, 'length': 0.49, 'type': '99', 'modes': 'cw'}]])

我有一个向量表示每行的前两个值(即 10017005,但是我需要另一个向量来表示与 'lanes'.[=17 关联的值=]

到目前为止,这是我的代码:

row_idx = edge_array[:, 0]
col_idx = edge_array[:, 1]
lane_values = edge_array[:, 2['lanes']]

我得到的错误如下:

lane_values = edge_array[:, 2['lanes']]
TypeError: 'int' object has no attribute '__getitem__'

如果您需要进一步说明,请告诉我,谢谢!

子表达式 2['lanes'] 没有意义:您正在索引数字 2。

相反,尝试:

[rec['lanes'] for rec in edge_array[:, 2]]

或:

import operator
map(operator.itemgetter('lanes'), edge_array[:,2])

以上给你一个正则Pythonlist;如果你想要一个 NumPy 数组,你必须在列表中调用 np.array()

但这里更好的解决方案是将您的数据转换为具有命名列的 "structured array",然后您可以按名称高效地建立索引。如果你的数组有很多行,这将对效率产生很大影响。

这不是一个完整的示例。很难与之合作。种类不清楚。我怀疑您以某种方式使用 numpy,但是很难说。

无论如何,2['something'] 的索引是不正确的,错误会告诉您原因。尝试使用整数中的键进行索引。在 python / numpy.

中查找索引是如何完成的

但这就是你可以提取你的'lanes':

的方式
map(lambda x: x['lanes'], edge_array[:, 2]))
# OR (if you want a vector/np-array)
vec_of_lanes = np.array(map(lambda x: x['lanes'], edge_array[:, 2])))

更多 numpy 风格:

vec_of_lanes = np.apply_along_axis(lambda x: x[2]['lanes'], 1, edge_array)

@Zwinck 建议使用结构化数组。这是一种方法

为字典部分定义一个数据类型。它有不同数据类型的字段

dt1 = np.dtype([('lanes',int), ('length',float), ('type','S2'),('modes','S2')])

将该数据类型嵌入到更大的数据类型中。我对前两个值使用了子数组格式:

dt = np.dtype([('f0',int,(2,)), ('f1',dt1)])

现在创建数组。我编辑了你的表情以适应 dt。元组和列表的混合很重要。我本可以从您的对象数组传输数据(待办事项?)

edge_array1 = np.array(  
    [([1001, 7005], ( 9,  0.35, '99','cw')),
     ([1001, 8259], ( 10, 0.46, '99','cw')),
     ([1001, 14007], (7,  0.49, '99', 'cw'))], dtype=dt)

现在可以通过 'f0' 字段名访问 2 个 int 值:

In [513]: edge_array1['f0']
Out[513]: 
array([[ 1001,  7005],
       [ 1001,  8259],
       [ 1001, 14007]])

而 'lanes' 通过字段名称索引的双重应用访问(因为它们是字段中的字段):

In [514]: edge_array1['f1']['lanes']
Out[514]: array([ 9, 10,  7])