【问题标题】:Populating a NumPy array using dictionary containing indices使用包含索引的字典填充 NumPy 数组
【发布时间】:2018-05-24 22:26:36
【问题描述】:

我正在尝试根据值字典填充一个 numpy 数组。

我的字典是这样的:

A = {(12, 15): 4, (532, 31): 7, (742, 1757): 1, ...}

我正在尝试填充数组,以便(使用我上面的示例)4 位于索引 (12,15) 处,依此类推。 A 中的键称为 'd','s',值称为 'count'。

A = {(d,s): 计数}

目前我填充数组的代码如下所示:

N = len(seen)
Am = np.zeros((N,N), 'i')
for key, count in A.items():
    Am[d,s] = count

但这只会导致创建多个数组,其中大部分都是零。

谢谢

【问题讨论】:

  • 什么是N?....
  • N是字典中s/d的最大值。

标签: python arrays numpy dictionary


【解决方案1】:

这是一种方法 -

def dict_to_arr(A):
    idx = np.array(list(A.keys()))
    val = np.array(list(A.values()))

    m,n = idx.max(0)+1 # max extents of indices to decide o/p array
    out = np.zeros((m,n), dtype=val.dtype)
    out[idx[:,0], idx[:,1]] = val # or out[tuple(idx.T)] = val
    return out

如果我们避免索引和值的数组转换并在最后一步直接使用它们进行分配,可能会更快 -

out[zip(*A.keys())] = list(A.values())

示例运行 -

In [3]: A = {(12, 15): 4, (532, 31): 7, (742, 1757): 1}

In [4]: arr = dict_to_arr(A)

In [5]: arr[12,15], arr[532,31], arr[742,1757]
Out[5]: (4, 7, 1)

存储到稀疏矩阵中

为了节省内存并可能获得性能,我们可能希望存储在稀疏矩阵中。让我们用csr_matrix 来做吧,就像这样 -

from scipy.sparse import csr_matrix

def dict_to_sparsemat(A):
    idx = np.array(list(A.keys()))
    val = np.array(list(A.values()))
    m,n = idx.max(0)+1
    return csr_matrix((val, (idx[:,0], idx[:,1])), shape=(m,n))

示例运行 -

In [64]: A = {(12, 15): 4, (532, 31): 7, (742, 1757): 1}

In [65]: out = dict_to_sparsemat(A)

In [66]: out[12,15], out[532,31], out[742,1757]
Out[66]: (4, 7, 1)

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多