pythonarrayssparse-matrix

flip rows of sparse array in python


I have a sparse array, say:

from scipy import sparse
a = sparse.lil_matrix((2,3),)
a[0] = [1, 2, 3]
a[1, 2] = 5

so it looks like:

(0, 0)  1.0
(0, 1)  2.0
(0, 2)  3.0
(1, 2)  5.0

I was wondering - is there an easy way to flip the rows (something like numpy.fliplr equivalent)? ...so I would get the output as:

(0, 0)  3.0
(0, 1)  2.0
(0, 2)  1.0
(1, 0)  5.0

Solution

  • One way would be to convert the array to csr format, and then manipulate the row indices:

    from scipy import sparse
    a = sparse.lil_matrix((2,3),)
    a[0] = [1, 2, 3]
    a[1, 2] = 5
    
    a = a.tocsr()
    a.indices = -a.indices + a.shape[1] - 1
    print(a)
    

    yields

      (0, 2)    1.0
      (0, 1)    2.0
      (0, 0)    3.0
      (1, 0)    5.0