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

lok*_*ysh 4 python numpy

我有一个 Numpy 2D 数组和一个标题列表。Numpy 数组的每一行都是一条要映射到头部列表的记录。最后,我想将每条记录转换为字典(因此有一个字典列表)。例如:

A = [[1, 2, 3], [4, 5, 6]]
headers = ['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

输出:

[{'a' : 1, 'b' : 2, 'c' : 3}, {'a' : 4, 'b' : 5, 'c' : 6}]
Run Code Online (Sandbox Code Playgroud)

在 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)
Run Code Online (Sandbox Code Playgroud)

Dan*_*ejo 5

使用zip + dict

result = [dict(zip(headers, l)) for l in A]
print(result)
Run Code Online (Sandbox Code Playgroud)

输出

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]
Run Code Online (Sandbox Code Playgroud)

随着zip您从列表中创建一对项目并将其传递给字典构造函数。