将一个Numpy二维数组转换为映射字典的列表

4

我有一个 NumPy 二维数组和一个头列表。NumPy 数组的每一行都是要映射到头列表的记录。最后,我希望将每个记录转换为一个字典(这样就有了一个字典列表)。例如:

A = [[1, 2, 3], [4, 5, 6]]
headers = ['a', 'b', 'c']

输出:

[{'a' : 1, 'b' : 2, 'c' : 3}, {'a' : 4, 'b' : 5, 'c' : 6}]

如何在Python中最快地实现这个?我有大约10^4行和10列标题,运行需要大约0.3秒。

目前,我的代码如下:

current_samples = A # The samples described above as input, a Numpy array
locations = []
for i, sample in enumerate(current_samples):
    current_location = dict()
    for index, dimension in enumerate(headers):
        current_location[dimension] = sample[index]
    locations.append(current_location)

有兴趣问一下,你的使用场景是什么,300毫秒似乎很慢?你是在评估可能性,还是一个网络服务..? - jtlz2
2个回答

5

使用 zip + dict


result = [dict(zip(headers, l)) for l in A]
print(result)

输出

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]

使用zip,您可以从列表中创建项目对,并将其传递给字典构造函数。

谢谢。我测试了一下,它将时间从0.3秒减少到了0.07秒。大约提高了4.5倍的效率。 - lokiysh

0
你可以(有点过度)使用 pandas 来实现这个目的:
result = pd.DataFrame(A, columns=headers).to_dict('row')

输出:

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接