简体   繁体   中英

Convert numpy matrix into 1D numpy array

I have the sum of a csr_matrix over one dimension, which returns a 1 dimensional vector. This is by default of the type numpy.matrix with shape (1, N). However, I want to represent this by a numpy.array with shape (N,). The following works:

>>> import numpy as np; import scipy.sparse as sparse
>>> a = sparse.csr_matrix([[0,1,0,0],[1,0,0,0],[0,1,2,0]])
>>> a
Out[15]: 
<3x4 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>
>>> a.todense()
Out[16]: 
matrix([[0, 1, 0, 0],
        [1, 0, 0, 0],
        [0, 1, 2, 0]], dtype=int64)
>>> a.sum(axis=0)
Out[17]: matrix([[1, 2, 2, 0]], dtype=int64)
>>> np.array(a.sum(axis=0)).ravel()
Out[18]: array([1, 2, 2, 0], dtype=int64)

However, this last step seems a bit overkill for a transformation from a numpy matrix to numpy array. Is there a function that I am missing that can do this for me? It shall pass the following unit test.

def test_conversion(self):
    a = sparse.csr_matrix([[0,1,0,0],[1,0,0,0],[0,1,2,0]])
    r = a.sum(axis=0)
    e = np.array([1, 2, 2, 0])
    np.testing.assert_array_equal(r, e)

The type numpy.matrix is already a subclass of numpy.ndarray , so no conversion needs to take place:

>>> np.ravel(a.sum(axis=0))
array([1, 2, 2, 0])

I'm not sure if this is essentially equivalent to what you have done, but it looks marginally neater:

a.sum(axis=0).A1

http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.A1.html#numpy.matrix.A1

A simple numpy hack to convert n-dimensional array to 1-d array.

import numpy as np 
a = np.array([[1],[2]])

array([[1] [2]])

a.reshape(len(a))

array([1, 2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM