【问题标题】:Formatting a dictionary with Python Numpy使用 Python Numpy 格式化字典
【发布时间】:2021-12-21 01:06:52
【问题描述】:

如何将 numpy 数组 a 设置为字典字典中的三个列表集 one, two, three,就像下面的预期输出一样?

import numpy as np 
set_names = np.array(['one', 'two', 'three'])
a = np.array([12,4,2,45,6,7,2,4,5,6,12,4])
dictionary = dict(zip(set_names, np.array_split(a, 3)))

预期输出:

{'one': array([12,  45,  2,  6]),
 'three': array([4, 6, 4, 12]),
 'two': array([2,  7,  5,  4])}

【问题讨论】:

  • set_names 应该只是一个列表,而不是一个 numpy 数组。 set_names = ['one', 'two', 'three'].

标签: python arrays numpy dictionary format


【解决方案1】:

Numpyreshape 方法,它可以重塑给定的数组:

注意:在重塑矩阵时,输出和输入矩阵的总元素必须相等。这就是你必须计算新形状的原因,或者你可以使用-1 作为其他重塑值。它将计算适合的值。

您可以使用以下方法重塑您的数组:

a.reshape((3, -1))

输出:

[[12  4  2 45]
 [ 6  7  2  4]
 [ 5  6 12  4]]

但这不是你要找的。让我们将其设为 3 列:

a.reshape((-1, 3))

输出:

[[12  4  2]
 [45  6  7]
 [ 2  4  5]
 [ 6 12  4]]

乍一看你可能看不到它。但这就是你想要的。但作为列。现在我们可以得到矩阵的transpose

np.transpose(a.reshape((-1, 3)))

输出:

[[12 45  2  6]
 [ 4  6  4 12]
 [ 2  7  5  4]]

最后但并非最不重要的是做你的字典:

import numpy as np

set_names = np.array(['one', 'two', 'three'])
a = np.array([12, 4, 2, 45, 6, 7, 2, 4, 5, 6, 12, 4])
dictionary = dict(zip(set_names, np.transpose(a.reshape((-1, 3)))))

输出:

{'one': array([12, 45,  2,  6]), 'two': array([ 4,  6,  4, 12]), 'three': array([2, 7, 5, 4])}

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2020-11-16
    • 2018-05-24
    • 2016-12-06
    相关资源
    最近更新 更多