python - 将具有已知索引的字典转换为多维数组

标签 python numpy dictionary

我有一个字典,其中的条目标记为 {(k,i): value, ...}。我现在想将这个字典转换成一个二维数组,其中为位置 [k,i] 的数组元素给出的值是标签为 (k,i )。行的长度不一定是相同的大小(例如,行 k = 4 可能上升到索引 i = 60 而行 k = 24 可能会上升到索引 i = 31)。由于不对称性,可以使特定行中的所有附加条目都等于 0 以获得矩形矩阵。

最佳答案

这是一种方法-

# Get keys (as indices for output) and values as arrays
idx = np.array(d.keys())
vals = np.array(d.values())

# Get dimensions of output array based on max extents of indices
dims = idx.max(0)+1

# Setup output array and assign values into it indexed by those indices
out = np.zeros(dims,dtype=vals.dtype)
out[idx[:,0],idx[:,1]] = vals

我们还可以使用稀疏矩阵来获得最终输出。例如与 coordinate format sparse matrices .当保存为稀疏矩阵时,这将是内存高效的。所以,最后一步可以用这样的东西代替 -

from scipy.sparse import coo_matrix

out = coo_matrix((vals, (idx[:,0], idx[:,1])), dims).toarray()

sample 运行-

In [70]: d
Out[70]: {(1, 4): 120, (2, 2): 72, (2, 3): 100, (5, 2): 88}

In [71]: out
Out[71]: 
array([[  0,   0,   0,   0,   0],
       [  0,   0,   0,   0, 120],
       [  0,   0,  72, 100,   0],
       [  0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0],
       [  0,   0,  88,   0,   0]])

为了使其对任意维数的 ndarray 通用,我们可以使用线性索引并使用 np.put 将值分配到输出数组中。因此,在我们的第一种方法中,只需将最后一步的赋值替换为类似这样的东西 -

np.put(out,np.ravel_multi_index(idx.T,dims),vals)

sample 运行-

In [106]: d
Out[106]: {(1,0,0): 99, (1,0,4): 120, (2,0,2): 72, (2,1,3): 100, (3,0,2): 88}

In [107]: out
Out[107]: 
array([[[  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0]],

       [[ 99,   0,   0,   0, 120],
        [  0,   0,   0,   0,   0]],

       [[  0,   0,  72,   0,   0],
        [  0,   0,   0, 100,   0]],

       [[  0,   0,  88,   0,   0],
        [  0,   0,   0,   0,   0]]])

关于python - 将具有已知索引的字典转换为多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729912/

相关文章:

javascript - 在 HTML 模板中使用 Javascript 检索 Flask JSON 对象

python - 选择行,使特定列包含列表中的值

python - recv_into 一个 numpy 数组

ios - 访问字典中的字典

python - 用每个可能的列创建一个矩阵

python - 您如何连接到 AWS Elastic Transcoder?

python - 如何检查列表中元素之间的约束/这是约束编程吗?

python - 仅当满足每行元素的条件时,才计算 2D 数组特定列的均值和方差

Python:如何分割包含额外分隔符作为值的字符串

xcode - swift 2.0 : Type of expression is ambiguous without more context (Using Parse)