探序基因肿瘤研究院

import scanpy as sc
>>> adata = sc.read_10x_h5('/xxx/filtered_feature_bc_matrix.h5')
/root/miniconda3/lib/python3.12/site-packages/anndata/_core/anndata.py:1756: UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
  utils.warn_names_duplicates("var")
/root/miniconda3/lib/python3.12/site-packages/anndata/_core/anndata.py:1756: UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
  utils.warn_names_duplicates("var")

报错应该是基因名字没有唯一。

>>> print(adata)
AnnData object with n_obs × n_vars = 3793 × 18085
    var: 'gene_ids', 'feature_types', 'genome'

保存变量:

import pickle

with open('processed_data.pkl', 'wb') as f: 

    pickle.dump(adata, f)

读取变量:

import pickle

with open('processed_data.pkl', 'rb') as f:

    adata = pickle.load(f)

查看adata.var:

将基因组位置存储在 adata.var 中。 "chromosome", "start", "end"分别保存每个基因的染色体以及在该染色体上的开始和结束位置。可以使用infercnvpy.io.genomic_position_from_gtf()函数。

下载了一个Homo_sapiens.GRCh38.99.gtf.gz文件,

infercnvpy.io.genomic_position_from_gtf("Homo_sapiens.GRCh38.99.gtf.gz",adata)
出现报错信息:

INFO:root:Extracted GTF attributes: ['gene_id', 'gene_version', 'gene_name', 'gene_source', 'gene_biotype', 'transcript_id', 'transcript_version', 'transcript_name', 'transcript_source', 'transcript_biotype', 'tag', 'transcript_support_level', 'exon_number', 'exon_id', 'exon_version', 'protein_id', 'protein_version', 'ccds_id']

应该是要解压缩

bdata变量查看:

>>> bdata
AnnData object with n_obs × n_vars = 3000 × 55556
    obs: 'age', 'sex', 'sample', 'patient', 'cell_type'
    var: 'ensg', 'mito', 'n_cells_by_counts', 'mean_counts', 'pct_dropout_by_counts', 'total_counts', 'n_counts', 'chromosome', 'start', 'end', 'gene_id', 'gene_name'
    uns: 'cell_type_colors', 'neighbors', 'umap', 'cnv'
    obsm: 'X_scVI', 'X_umap', 'X_cnv'
    obsp: 'connectivities', 'distances'

查看细胞注释数据:

>>> bdata.obs['cell_type']
Run
SRR10796381         T cell CD4
SRR10787713         Macrophage
SRR10785570         T cell CD4
SRR10790048           Monocyte
SRR10782528    Epithelial cell
                    ...       
SRR10782593         Fibroblast
SRR10789971    Epithelial cell
SRR10780468    Epithelial cell
SRR10779840                mDC
SRR10795768              other
Name: cell_type, Length: 3000, dtype: category
Categories (21, object): ['Alevolar cell type 1', 'Alevolar cell type 2', 'B cell', 'Ciliated', ...,
                          'T cell regulatory', 'mDC', 'other', 'pDC']

这种数据结构是Pandas库的DataFrame。DataFrame是Pandas库中的一种二维标签数据结构,可以看作是一种带有行和列标签的表格数据。它既有行索引,也有列索引,每列可以是不同的数据类型。DataFrame类似于电子表格或SQL表格,非常适合用于数据分析和处理。

>>> bdata.obs['cell_type'][1:3]
Run
SRR10787713    Macrophage
SRR10785570    T cell CD4
Name: cell_type, dtype: category
Categories (21, object): ['Alevolar cell type 1', 'Alevolar cell type 2', 'B cell', 'Ciliated', ...,
                          'T cell regulatory', 'mDC', 'other', 'pDC']

>>> bdata.obs["cell_type"].iloc[0]
'T cell CD4'

可通过bdata.obs["cell_type"].iloc[0] = “xxx” 的方式来修改细胞类型。

读取细胞名:

ind = bdata.obs["cell_type"].index

>>> print(ind)
Index(['SRR10796381', 'SRR10787713', 'SRR10785570', 'SRR10790048',
       'SRR10782528', 'SRR10783499', 'SRR10782527', 'SRR10795166',
       'SRR10798281', 'SRR10791041',
       ...
       'SRR10795296', 'SRR10785910', 'SRR10779352', 'SRR10790560',
       'SRR10779232', 'SRR10782593', 'SRR10789971', 'SRR10780468',
       'SRR10779840', 'SRR10795768'],
      dtype='object', name='Run', length=3000)

>>> ind[1:5]
Index(['SRR10787713', 'SRR10785570', 'SRR10790048', 'SRR10782528'], dtype='object', name='Run')

对AnnData中的obs中的列名进行改名:raw为新的列名的列表,["c1","c2","c3",...]

adata_st.obs.columns = raw

如何创建:

import pandas as pd
创建一个包含分类数据的DataFrame:

案例1:
df = pd.DataFrame({
    'A': pd.Categorical(['apple', 'banana', 'apple', 'banana'], categories=['apple', 'banana']),
    'B': pd.Categorical(['b', 'a', 'b', 'a'], categories=['b', 'a'])
})
# 将列的dtype设置为category
df = df.astype({'A': 'category', 'B': 'category'})

案例2:

data = {'Name': ['Alice', 'Bob', 'Charlie'],
             'Age': [25, 30, 35],
             'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)
print(df)

案例3:设置行名

data = {'Column1': [1, 2, 3], 'Column2': [4, 5, 6]}

row_names = ['Row1', 'Row2', 'Row3']

df = pd.DataFrame(data, index=row_names)

或者:

df = df.reset_index(drop=True)  # 重置索引,不保留旧索引作为列

df.index = row_names  # 设置新的行名

print(df)

scanpy数据结构保存方法:

adata.write('annotation_data.h5ad')

;python数据结构类型:数组、列表、元组、集合、字典、堆、栈、队列、树、图等

>>> cnv.pl.chromosome_heatmap(bdata, groupby="cell_type")
/root/miniconda3/lib/python3.12/site-packages/scanpy/plotting/_utils.py:363: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  plt.show()

参考:

单细胞转录组实战04: infercnvpy识别恶性细胞

AnnData 教程 1:开始使用 anndata-CSDN博客

数据存储格式——Anndata-CSDN博客

Pandas 数据结构——DataFrame_pandas dataframe-CSDN博客

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐