Reading and Writing
Reading and writing AnnData objects.
Reading¶
Use anndata.io.read_h5ad to load a previously saved .h5ad file, or val.datasets.polis.load to import directly from a Polis conversation.
Writing¶
valency_anndata.write ¶
write(
filename: Path | str,
adata: AnnData,
*,
include: Sequence[str] | None = None,
ext: Literal["h5", "csv", "txt", "npz"] | None = None,
compression: Literal["gzip", "lzf"] | None = "gzip",
compression_opts: int | None = None,
) -> None
Write an AnnData object to file with automatic sanitization.
Wraps scanpy.write but first copies and sanitizes adata so that
problematic fields (mixed-type uns["statements"] columns) do not
cause serialization errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
Path | str
|
Output path. If the filename has no file extension it is interpreted the same way as scanpy.write. |
required |
adata
|
AnnData
|
Annotated data matrix. Not mutated — a sanitized copy is written. |
required |
include
|
Sequence[str] | None
|
When not |
None
|
ext
|
Literal['h5', 'csv', 'txt', 'npz'] | None
|
File extension from which to infer file format. |
None
|
compression
|
Literal['gzip', 'lzf'] | None
|
See |
'gzip'
|
compression_opts
|
int | None
|
See |
None
|
Notes
Cluster labels and missing values.
Clustering columns (kmeans_*) are stored as
categorical arrays <https://anndata.readthedocs.io/en/latest/fileformat-prose.html>_
in the h5ad file. The on-disk encoding uses integer codes that index
into a categories array, with -1 reserved for missing entries.
This means two distinct "absent" semantics survive the round-trip:
- Label
-1(e.g. HDBSCAN noise points) is a real category in the categories array. It is a valid cluster assignment meaning "this participant was clustered but not assigned to any group." NaN/pd.NAmeans the participant was never part of the clustering subset (e.g. excluded bymask_obs). On disk this is represented by code-1, which points to no category.
After reading the file back with :func:anndata.read_h5ad, you can
distinguish the two with :func:pandas.isna::
labels = adata.obs["kmeans_polis"]
noise = labels == -1 # clustered, but no group
unseen = labels.isna() # not in the clustering subset
Examples:
Basic — write everything:
Advanced — selectively include keys with glob patterns:
val.write(
"export.h5ad",
adata,
include=["obsm/X_pca", "obsm/X_pacmap", "obs/kmeans_*", "uns/*"],
)
Source code in src/valency_anndata/_write.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |