2

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)
1
  • Notice that while a itself is a sparse matrix, the sum is a np.matrix. Shortcuts like .A1 that work with the later don't work on the sparse one. Commented Feb 19, 2015 at 17:07

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.