user10163680
user10163680

Reputation: 263

How to print whole sparse matrix?

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)

Upvotes: 6

Views: 11200

Answers (3)

Adam
Adam

Reputation: 17379

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, fill_value=0.)

yields:

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

For a more compact view with blank spaces instead of zeros, mprint(X, title=None, indices=False):

┌          ┐
│      0.5 │
│ 0.5      │
└          ┘

Upvotes: 2

Harsh Shah
Harsh Shah

Reputation: 157

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

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70999

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)

Upvotes: 10

Related Questions