如何将带有坐标和频率的字典转换为矩阵?

2024-03-29 02:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典看起来像:

data = {(-1.0, 4.0): 1, (2.0, 2.0): 12, (3.0, 1.0): 8}

我想做一个矩阵,看起来像:

[[0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]
 [0. 0. 0. 12. 0.]
 [0. 0. 0. 0. 8.]
 [0. 0. 0. 0. 0.]]

字典中的每个键都是我矩阵中的“坐标”(从左下角开始),轴的限制由我定义(xlim:-3,13,ylim:-6,8)未显示。你知道吗

我试着这样做:

matrix = np.zeros((5,5))
for (x, y), z in data.items():
    x = int(x)
    y = int(y)

    matrix[y,x] = z

但是我在负维度上有错误。你知道吗

我的最终目标是将我的字典绘制成某种直方图,其中坐标是x,y,字典值(freq)是我的z维或“深度”。你知道吗


Tags: infordata字典定义错误npzeros
3条回答

Numpy不会给出负索引的错误,但它会从最后一个索引它,这不是你想要的。 你为你的矩阵选择了错误的维度。下面的代码计算矩阵的大小以适应所有的位置,然后移动位置坐标以适应矩阵,在本例中为-3和-6

xlim = (-3, 13)
ylim = (-6,8)

# your array dimension must be
dim = xlim[1] - xlim[0], ylim[1]-ylim[0]

matrix = np.zeros(dim)

for (x, y), z in data.items():
    # this will also work for +ve lower limit
    x_new = int(x-xlim[0])
    y_new = int(y-ylim[0])

    # negetive sign because we want the index to start from bottom left
    matrix[-x_new, y_new] = z

print(matrix)


# if you want to remove rows and colums with all zeros
new_matrix = matrix[np.sum(matrix, axis=1)>0]
new_matrix = new_matrix[:,np.sum(matrix, axis=0)>0].copy()
print("\n",new_matrix)

numpy允许负索引 然后您可以使用:

np.rot90(matrix, 1)

它将[0,0]移到左下角

与前面的建议类似,“移动”矩阵到正区域,然后使用x和y偏移定位坐标:

import numpy as np
data = {(-1.0, 4.0): 1, (2.0, 2.0): 12, (3.0, 1.0): 8}
x_offset = 3
y_offset = 6
mat = np.zeros((17, 15))
for (x, y), z in data.items():
    mat[int(y + y_offset), int(x + x_offset)] = z

编辑

好吧,我想这就是你的想法(我假设在x和y坐标中都有负值):

如果要硬编码x和y值的范围(xlim:-3、13、ylim:-6、8):

x_min, x_max = -3, 13
y_min, y_max = -6, 8

或根据数据确定:

x_min = min([x for (x, y), z in data.items()])
y_min = min([y for (x, y), z in data.items()])
x_max = max([x for (x, y), z in data.items()])
y_max = max([y for (x, y), z in data.items()])

然后使用:

x_offset = abs(x_min)
y_offset = abs(y_min)

mat = np.zeros((y_max + y_offset + 1, x_max + x_offset + 1))    # (Row, column) becomes (y, x)

for (x, y), z in data.items():
    print(x, y)
    mat[int(y + y_offset), int(x + x_offset)] = z

pd.DataFrame(mat, columns=range(x_min, x_max + 1), 
                  index=range(y_min, y_max + 1))

然后使用以下公式绘图:

plt.imshow(mat, origin='lower', extent=[x_min, x_max + 1, 
                                        y_min, y_max + 1])

相关问题 更多 >