擅长:python、mysql、java
<p>Numpy不会给出负索引的错误,但它会从最后一个索引它,这不是你想要的。
你为你的矩阵选择了错误的维度。下面的代码计算矩阵的大小以适应所有的位置,然后移动位置坐标以适应矩阵,在本例中为-3和-6</p>
<pre><code>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)
</code></pre>