5

I want to print the whole matrix. When I print X it tells me location where values are stored expcept zeros. Can I print whole matrix including zeros?

X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]]))
print(X)
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
user10163680
  • 253
  • 2
  • 11
  • 1
    [This answer](https://stackoverflow.com/a/22965622/832621) might be helpful. It shows how to visualize such matrix without converting it to a dense matrix (which usually is not possible due to memory constraints) – Saullo G. P. Castro Feb 12 '20 at 10:12

3 Answers3

7

You can convert the sparse matrix to dense (i.e. regular numpy matrix) and then print the dense representation. For this use the method todense.

Sample code:

X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]]))
a = X.todense()
print(a)
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
2

If you want to just print. You can simply use toarray() method and convert it to an array. Similarly, you can also convert it into a data frame to perform any pandas operations using the pandas Dataframe() method.

X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]]))
print(X.toarray())
X_df =pd.DataFrame(X.toarray())
X_df
Harsh Shah
  • 147
  • 1
  • 3
0

matrepr prints sparse matrices directly, without conversions to other formats:

X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]]))

from matrepr import mprint
mprint(X)

yields:

<2×2, 2 'float64' elements, csr>
     0    1
  ┌          ┐
0 │      0.5 │
1 │ 0.5      │
  └          ┘

For a more compact view, mprint(X, title=None, indices=False):

┌          ┐
│      0.5 │
│ 0.5      │
└          ┘
Adam
  • 16,808
  • 7
  • 52
  • 98