不失一般性,下面是通过numpy 和collections.defaultdict 的解决方案。
结果是一个嵌套字典,其中外键是行号,内键是列号。
该解决方案可以适应您的问题和所需的输出。您可能希望查看pandas 以分别提取行号、列名和数据以用于以下算法。
from collections import defaultdict
import numpy as np
arr = np.array([[0, 134, 0, 451, 0],
[234, 0, 4513, 0, 0],
[0, 0, 132, 34, 0],
[452, 562, 0, 0, 0]])
d = defaultdict(lambda: defaultdict(int))
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
val = arr[i, j]
if val != 0:
d[i+1][j+1] = val
结果
defaultdict(<function __main__.<lambda>>,
{1: defaultdict(int, {2: 134, 4: 451}),
2: defaultdict(int, {1: 234, 3: 4513}),
3: defaultdict(int, {3: 132, 4: 34}),
4: defaultdict(int, {1: 452, 2: 562})})