Skip to content

Instantly share code, notes, and snippets.

@cannin
Last active October 6, 2022 15:04
Show Gist options
  • Save cannin/b5b5f67560af85c26fb9823f94920632 to your computer and use it in GitHub Desktop.
Save cannin/b5b5f67560af85c26fb9823f94920632 to your computer and use it in GitHub Desktop.
import numpy as np
import pandas as pd
import anndata as ad
# Generate example data and build AnnData object
vals = np.random.rand(5, 10).astype('f')
adata = ad.AnnData(vals)
adata
adata.X
adata.obs_names = [f"cell_{i:d}" for i in range(adata.n_obs)]
adata.var_names = [f"gene_symbol_{i:d}" for i in range(adata.n_vars)]
print(adata.obs_names[:3])
tmp = np.random.choice(["cell1", "cell2", "cell3"], size=(adata.n_obs,))
adata.obs["cell_type1_id"] = tmp
adata.obs
tmp = np.random.choice(["cell_type1", "cell_type2", "cell_type3"], size=(adata.n_obs,))
adata.obs["cell_type2_id"] = tmp
adata.obs
tmp = np.random.choice(["G1", "G2", "G3"], size=(adata.n_vars,))
adata.var["gene_type1_id"] = tmp
adata.var
tmp = np.random.choice(["gene_type1", "gene_type2", "gene_type3"], size=(adata.n_vars,))
adata.var["gene_type2_id"] = tmp
adata.var
bdata = adata[adata.obs.cell_type1_id == "cell1"]
bdata
# Write tables
adata.write_csvs("output", skip_data=False)
# Write h5ad format
adata.write(filename="anndata.h5ad")
# Read data
cdata = ad.read_h5ad(filename="anndata.h5ad")
cdata
cell_type1_id cell_type2_id
cell_0 cell1 cell_type3
cell_1 cell3 cell_type1
cell_2 cell3 cell_type2
cell_3 cell1 cell_type3
cell_4 cell3 cell_type1
gene_type1_id gene_type2_id
gene_symbol_0 G1 gene_type2
gene_symbol_1 G1 gene_type3
gene_symbol_2 G1 gene_type1
gene_symbol_3 G1 gene_type2
gene_symbol_4 G2 gene_type3
gene_symbol_5 G2 gene_type2
gene_symbol_6 G1 gene_type2
gene_symbol_7 G2 gene_type2
gene_symbol_8 G3 gene_type3
gene_symbol_9 G2 gene_type2
0.19100112 0.46828908 0.8881515 0.3272082 0.44101298 0.13238761 0.06625041 0.42884535 0.45125055 0.54849786
0.73450327 0.968179 0.44648758 0.10997138 0.2849175 0.5890882 0.053468592 0.7258484 0.8558861 0.28162476
0.34389842 0.6496306 0.70850253 0.5590548 0.93613046 0.18099453 0.2924698 0.13112783 0.25727338 0.29037902
0.67264825 0.36550987 0.7641897 0.5965308 0.30332556 0.7546757 0.88458216 0.6731449 0.1464198 0.2685193
0.59329206 0.8943774 0.061935168 0.20078066 0.16109781 0.0445861 0.456919 0.34288594 0.4962387 0.3457089
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment