数组的点和值字典

时间:2014-04-26 16:01:25

标签: python numpy dictionary matrix

我有一对坐标对和整数的字典。第一个问题是有些观点是消极的。

{(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}

to 

+---+---+---+
| 0 | 0 | 4 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 2 | 0 | 3 |
+---+---+---+

我相信我必须调整所有对,因此它们大于零,所以我可以将它们用作矩阵的行,列对。然后插入是下一个。我相信python只有嵌套列表而不是矩阵所以我想要一个numpy数组。

3 个答案:

答案 0 :(得分:1)

import numpy as np


def make_array(data):
    # In your example row is the second index and col is the first.
    # Also positive row indexes go in up direction.
    c, r = np.array(zip(*data.keys()))

    rows = r.max()-r.min()+1
    cols = c.max()-c.min()+1

    result = np.zeros((rows, cols), dtype=int)

    for k, v in data.iteritems():
        # Minus before first index required for 
        # the last row contain 2, 0, 3 in the example.
        # Also numpy successfully handle negative indexes
        # and inversion not required
        result[-k[1]+1, k[0]+1] = v

    return result

您的测试用例:

data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}
print make_array(data)

结果:

[[0 0 4]
 [0 1 0]
 [2 0 3]]

具有不同行和列的示例计数:

data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 1): 5}
print make_array(data)

结果:

   ----------- "-First" column
  |      ----- Second column
  |     |
[[0 0 4 5]     <-- First row
 [0 1 0 0]     <-- Zero row
 [2 0 3 0]]    <-- "-First" row

答案 1 :(得分:1)

使用纯Python:

def solve(d):

    x_min, y_min = map(min, zip(*d))
    x_max, y_max = map(max, zip(*d)) 

    arr = [[0]*(x_max-x_min+1) for _ in xrange(y_max-y_min+1)]

    for i, y in enumerate(xrange(y_min, y_max+1)):
        for j, x in enumerate(xrange(x_min, x_max+1)):
            arr[i][j] = d.get((x, y), 0)
    return arr[::-1]

输出:

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4})
Out[80]: 
[[0, 0, 4],
[0, 1, 0],
[2, 0, 3]]

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 2):30, (-3, -4):100})
Out[82]: 
[[0, 0, 0, 0, 0, 30],
 [0, 0, 0, 0, 4, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 0, 2, 0, 3, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [100, 0, 0, 0, 0, 0]]

答案 2 :(得分:0)

import numpy
s = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}
x = numpy.array([k+(v,) for k,v in s.iteritems()])
x[:,0]-=x[:,0].min()
x[:,1]-=x[:,1].min()
w = numpy.zeros((x[:,0].max()+1,x[:,1].max()+1))
w[x[:,:2].T.tolist()]=x[:,2]

resut:

>>> w
array([[ 2.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 3.,  0.,  4.]])