Mat*_*s24 5 python dictionary numpy
我有一本字典,标有的条目{(k,i): value, ...}。我现在想将此字典转换为2d数组,其中该位置的数组元素[k,i]的值是带有label的字典中的值(k,i)。行的长度不必一定是相同的大小(例如,行k = 4可能上升到索引,i = 60而行k = 24可能上升到index 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
Run Code Online (Sandbox Code Playgroud)
我们还可以使用稀疏矩阵来获得最终输出。例如与coordinate format sparse matrices. 当保存为稀疏矩阵时,这将提高内存效率。所以,最后一步可以用这样的东西代替 -
from scipy.sparse import coo_matrix
out = coo_matrix((vals, (idx[:,0], idx[:,1])), dims).toarray()
Run Code Online (Sandbox Code Playgroud)
样本运行 -
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]])
Run Code Online (Sandbox Code Playgroud)
为了使其对任意维数的 ndarray 通用,我们可以使用线性索引并使用np.put将值分配到输出数组中。因此,在我们的第一种方法中,只需将赋值的最后一步替换为类似这样的内容 -
np.put(out,np.ravel_multi_index(idx.T,dims),vals)
Run Code Online (Sandbox Code Playgroud)
样本运行 -
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]]])
Run Code Online (Sandbox Code Playgroud)