# Store data as sparse matrix

**URL:** <https://discourse.scverse.org/t/store-data-as-sparse-matrix/405>\
**Category:** anndata\
**Created:** [April 17, 2022, 1:08pm UTC](https://discourse.scverse.org/t/store-data-as-sparse-matrix/405 "2022-04-17T13:08:22Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![wangjiawen2013](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/wangjiawen2013/32/25_2.png) [@wangjiawen2013](https://discourse.scverse.org/u/wangjiawen2013)\
**Post date:** [April 17, 2022, 1:08pm UTC](https://discourse.scverse.org/t/store-data-as-sparse-matrix/405/1 "2022-04-17T13:08:22Z")

</div>

Hi,  
The raw data and scaled data are stored in numpy arrays in my anndata object for some reason, how to convert them to sparse data to save the hard disk storage ?

---

<div class="post-metadata">

**Author:** ![Valentine\_Svensson](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/valentine_svensson/32/10_2.png) [@Valentine\_Svensson](https://discourse.scverse.org/u/Valentine_Svensson)\
**Post date:** [April 19, 2022, 2:58am UTC](https://discourse.scverse.org/t/store-data-as-sparse-matrix/405/2 "2022-04-19T02:58:52Z")

</div>

Hi,

For the raw data you can do this:

```auto
from scipy import sparse

sparse_X = sparse.csr_matrix(adata.X)
adata.X = sparse_X

```

If your transformed data is sparse the same pattern will work. However, transformed data is generally not sparse.

Best,  
/Valentine

---

<div class="post-metadata">

**Author:** ![ivirshup](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/ivirshup/32/160_2.png) [@ivirshup](https://discourse.scverse.org/u/ivirshup)\
**Post date:** [April 19, 2022, 8:41am UTC](https://discourse.scverse.org/t/store-data-as-sparse-matrix/405/3 "2022-04-19T08:41:14Z")

</div>

@wangjiawen2013 An aside, but I would also make sure you are compressing your data while saving it. E.g. `adata.write_h5ad(..., compression="gzip")`.

---

<div class="post-metadata">

**Author:** ![wangjiawen2013](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/wangjiawen2013/32/25_2.png) [@wangjiawen2013](https://discourse.scverse.org/u/wangjiawen2013)\
**Post date:** [April 19, 2022, 12:48pm UTC](https://discourse.scverse.org/t/store-data-as-sparse-matrix/405/4 "2022-04-19T12:48:34Z")

</div>

I have never compressed adata, but I’ll try.
