Numpy Record Matrix:只记录记录矩阵中所有列的一个字段

时间:2015-05-26 20:08:14

标签: python numpy

我有一个numpy记录矩阵。我用这一行初始化了它的每一行:

r = np.recarray((len(list)), dtype=[('x', int), ('y', int), ('value', int)])

然后我使用vstack来堆叠行来制作矩阵:

supermatrix = np.vstack((supermatrix, r))

这最终给了我一个矩阵:

[[(0, 0, 0) (1, 0, 1) (2, 0, 0) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]
 [(0, 0, 0) (1, 0, 1) (2, 0, 1) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]
 [(0, 0, 0) (1, 0, 1) (2, 0, 0) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]
 ..., 
 [(0, 0, 0) (1, 0, 1) (2, 0, 1) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]
 [(0, 0, 0) (1, 0, 1) (2, 0, 0) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]
 [(0, 0, 0) (1, 0, 1) (2, 0, 1) ..., (34, 34, 0) (35, 34, 1) (35, 35, 0)]]

我想只对每列中的一个元素字段求和。

我知道numpy有一个np.sums(axis=1)方法可用于普通的numpy矩阵,但是我无法弄清楚如何将它只用于一个字段。

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这就是你要找的东西:

In [87]: r = np.ones((10,), dtype=[('x', int), ('y', int), ('value', int)])

In [88]: s=np.vstack((r,r,r,r))

In [89]: s
Out[89]: 
array([[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1),
        (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)],
       [(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1),
        (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)],
       [(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1),
        (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)],
       [(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1),
        (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]], 
      dtype=[('x', '<i4'), ('y', '<i4'), ('value', '<i4')])

In [90]: s['x']
Out[90]: 
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

In [91]: s['x'].sum(axis=1)
Out[91]: array([10, 10, 10, 10])

s['x']为您提供一个二维数组,其中只包含“x”字段中的值。您可以对其应用常规数组操作。