Error when saving adata with adata.write_h5ad(): "Above error raised while writing key 'names' of to /"

When I am trying to save anndata with adata.write_h5ad(), I am encountering the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File ~/miniconda3/envs/scanpy/lib/python3.11/site-packages/anndata/_io/utils.py:246, in report_write_key_on_error..func_wrapper(*args, **kwargs)
    245 try:
--> 246     return func(*args, **kwargs)
    247 except Exception as e:

File ~/miniconda3/envs/scanpy/lib/python3.11/site-packages/anndata/_io/specs/registry.py:311, in Writer.write_elem(self, store, k, elem, dataset_kwargs, modifiers)
    310 else:
--> 311     return write_func(store, k, elem, dataset_kwargs=dataset_kwargs)

File ~/miniconda3/envs/scanpy/lib/python3.11/site-packages/anndata/_io/specs/registry.py:52, in write_spec..decorator..wrapper(g, k, *args, **kwargs)
     50 @wraps(func)
     51 def wrapper(g, k, *args, **kwargs):
---> 52     result = func(g, k, *args, **kwargs)
     53     g[k].attrs.setdefault("encoding-type", spec.encoding_type)

File ~/miniconda3/envs/scanpy/lib/python3.11/site-packages/anndata/_io/specs/methods.py:415, in write_recarray(f, k, elem, _writer, dataset_kwargs)
    412 @_REGISTRY.register_write(H5Group, (np.ndarray, "V"), IOSpec("rec-array", "0.2.0"))
    413 @_REGISTRY.register_write(H5Group, np.recarray, IOSpec("rec-array", "0.2.0"))
    414 def write_recarray(f, k, elem, _writer, dataset_kwargs=MappingProxyType({})):
--> 415     f.create_dataset(k, data=_to_hdf5_vlen_strings(elem), **dataset_kwargs)

File ~/miniconda3/envs/scanpy/lib/python3.11/site-packages/h5py/_hl/group.py:183, in Group.create_dataset(self, name, shape, dtype, data, **kwds)
    181         group = self.require_group(parent_path)
...
    233     ) from e

TypeError: Can't implicitly convert non-string objects to strings

Above error raised while writing key 'names' of  to /

I don’t know what is the key names mentioned here and what may have caused the problem.
Thanks.

I found the source of the problem here.
The problem arises when scanpy.tl.rank_genes_groups() and scanpy.tl.filter_rank_genes_groups() are run. It’s resolved after deleting ‘rank_gene_groups_filtered’ and ‘rank_genes_groups’.

del adata.uns['rank_genes_groups_filtered']
del adata.uns['rank_genes_groups']
1 Like

uns_1 = adata.uns[‘rank_genes_groups_filtered’]
uns_2 = adata.uns[‘rank_genes_groups’]

Converting values to strings

adata.uns[‘rank_genes_groups_filtered’]= {key: str(value) for key, value in uns_1.items()}
adata.uns[‘rank_genes_groups’]= {key: str(value) for key, value in uns_2.items()}