GitHub日榜趋势速报:Python、TypeScript、Go项目筛选与开发者学习指南
2026/10/3 11:20:56
在生物信息学数据分析中,我们需要将AnnData数据转换为DataFrame数据,DataFrame数据的行为位点(细胞),列为基因。这种转换使得数据更容易处理和分析。
数据转换包含以下几个关键步骤:
importscanpyasscimportnumpyasnpimportpandasaspdfromscipyimportstatsdeftransform_dataframe(h5ad_file):""" 将AnnData数据转换为DataFrame数据 参数: h5ad_file: H5AD格式文件路径 返回: adata: AnnData对象 result_dataframe: 转换后的DataFrame数据 """# 读取H5AD文件adata=sc.read_h5ad(h5ad_file)# 标准化数据,使每个细胞的总reads数为10,000sc.pp.normalize_total(adata,target_sum=1e4)# 对数变换,使用log1p函数对数据进行对数变换sc.pp.log1p(adata)# 识别高变基因sc.pp.highly_variable_genes(adata,n_top_genes=3000)# 只保留高变基因adata=adata[:,adata.var['highly_variable']]# 将稀疏矩阵转换为密集矩阵X=adata.X.toarray()# 获取索引和列名index_list=adata.obs['ground_truth'].tolist()column=adata.var.index.tolist()# 创建DataFrameresult_dataframe=pd.DataFrame(data=X,index=index_list,columns=column)returnadata,result_dataframe# 使用示例adata,data=transform_dataframe("151507.h5ad")# 查看数据前10行print(data.head(10))# 查看特定细胞类型的数据print(data.loc['Layer1',:])数据转换后的DataFrame具有以下特征:
数据示例:
LINC00115 FAM41C SAMD11 PERM1 ISG15 AL390719.2 B3GALT6 Layer1 0.0 0.0 0.0 0.0 2.446558 0.0 0.000000 Layer1 0.0 0.0 0.0 0.0 0.000000 0.0 0.000000 ...差异表达基因分析是生物信息学中的重要分析任务,用于识别在不同条件下表达水平显著不同的基因。通过分析差异表达基因,我们可以理解细胞类型、疾病状态、处理条件等对基因表达的影响。
Wilcoxon秩和检验(Mann-Whitney U检验)是一种非参数检验方法,用于比较两组独立样本的分布差异。在生物信息学中,Wilcoxon检验被广泛应用于差异表达基因分析,原因包括:
下面设计的函数为嵌入最深的函数,或者说是含有底层数据处理逻辑的函数。该函数用于计算单个基因在目标组和背景组之间的差异表达情况。
defcompute(target_gene,background_gene,gene_name,cluster):""" 计算单个基因的差异表达统计量 参数: target_gene: 目标组的基因表达值 background_gene: 背景组的基因表达值 gene_name: 基因名称 cluster: 存储结果的字典 返回: None,结果直接存储在cluster字典中 """# 初始化基因信息cluster[gene_name]={}# 计算Wilcoxon秩和检验的p值stat,p_value=stats.mannwhitneyu(target_gene,background_gene,alternative='two-sided')# 计算log2 fold changepseudo_count=1# 避免除以零mean1=np.mean(target_gene)+pseudo_count mean2=np.mean(background_gene)+pseudo_count log_fc=np.log2(mean1/mean2)# 存储结果cluster[gene_name]['p_value']=p_value cluster[gene_name]['log_fc']=log_fc# 使用示例cluster={}gene_name='rand'# 创建模拟数据target_gene=np.random.normal(loc=5,scale=1,size=(10,))background_gene=np.random.randn(100)# 计算差异表达compute(target_gene,background_gene,gene_name,cluster)# 查看结果print(cluster)输出示例:
{ 'rand': { 'p_value': 2.0631739856825891e-07, 'log_fc': 2.6310103643667038 } }在底层处理函数的基础上,往外走一步。这一步要处理的是两个矩阵:目标细胞类型的表达矩阵和背景细胞类型的表达矩阵,对所有基因进行批量差异表达分析。
defbatch_de_analysis(data,target_cluster):""" 批量差异表达分析 参数: data: DataFrame格式的表达数据 target_cluster: 目标细胞类型名称 返回: results: 所有基因的差异表达结果字典 """# 提取目标细胞类型的数据target_data=data.loc[data.index==target_cluster,:]# 提取背景细胞类型的数据(除目标细胞类型外的所有数据)background_data=data.loc[data.index!=target_cluster,:]# 初始化结果字典results={}# 对每个基因进行差异表达分析forgeneindata.columns:target_gene=target_data[gene].values background_gene=background_data[gene].values compute(target_gene,background_gene,gene,results)returnresults# 使用示例target_cluster="Layer1"results=batch_de_analysis(data,target_cluster)# 查看部分结果fori,(gene,stats)inenumerate(list(results.items())[:10]):print(f"{gene}: p_value={stats['p_value']:.2e}, log_fc={stats['log_fc']:.4f}")输出示例:
LINC00115: p_value=6.88e-01, log_fc=0.0042 FAM41C: p_value=7.43e-01, log_fc=0.0031 SAMD11: p_value=7.98e-01, log_fc=0.0039 PERM1: p_value=5.23e-01, log_fc=-0.0021 ISG15: p_value=6.22e-09, log_fc=-0.1414 AL390719.2: p_value=8.48e-01, log_fc=0.0002 B3GALT6: p_value=1.49e-02, log_fc=-0.0289 MXRA8: p_value=9.17e-01, log_fc=0.0238 VWA1: p_value=1.97e-02, log_fc=-0.0256 CDK11B: p_value=2.51e-04, log_fc=-0.0524在进行大量基因的差异表达分析时,由于进行了多次假设检验,需要进行多重检验校正,以控制假阳性率。常用的校正方法包括:
fromstatsmodels.stats.multitestimportmultipletestsdefbonferroni_correction(results):""" 使用Bonferroni方法进行多重检验校正 参数: results: 差异表达结果字典 返回: results: 添加了校正后p值的结果字典 """# 提取所有p值p_values=[results[gene]['p_value']forgeneinresults]# 进行Bonferroni校正reject,p_corrected,_,_=multipletests(p_values,alpha=0.05,method='bonferroni')# 将校正后的p值添加到结果中fori,geneinenumerate(results):results[gene]['p_corrected']=p_corrected[i]results[gene]['significant']=reject[i]returnresultsdeffdr_correction(results):""" 使用Benjamini-Hochberg方法进行FDR校正 参数: results: 差异表达结果字典 返回: results: 添加了FDR校正后p值的结果字典 """# 提取所有p值p_values=[results[gene]['p_value']forgeneinresults]# 进行FDR校正reject,p_corrected,_,_=multipletests(p_values,alpha=0.05,method='fdr_bh')# 将校正后的p值添加到结果中fori,geneinenumerate(results):results[gene]['fdr']=p_corrected[i]results[gene]['significant']=reject[i]returnresults根据统计检验结果和设定的阈值,筛选出显著的差异表达基因。
deffilter_de_genes(results,p_threshold=0.05,logfc_threshold=1.0):""" 筛选差异表达基因 参数: results: 差异表达结果字典 p_threshold: p值阈值 logfc_threshold: log2 fold change阈值 返回: up_genes: 上调基因列表 down_genes: 下调基因列表 """up_genes=[]down_genes=[]forgene,statsinresults.items():# 判断基因是否显著is_significant=stats.get('significant',stats['p_value']<p_threshold)ifis_significant:ifstats['log_fc']>=logfc_threshold:up_genes.append({'gene':gene,'p_value':stats['p_value'],'log_fc':stats['log_fc']})elifstats['log_fc']<=-logfc_threshold:down_genes.append({'gene':gene,'p_value':stats['p_value'],'log_fc':stats['log_fc']})# 按log_fc排序up_genes.sort(key=lambdax:x['log_fc'],reverse=True)down_genes.sort(key=lambdax:x['log_fc'])returnup_genes,down_genes# 使用示例# 首先进行多重检验校正results=fdr_correction(results)# 筛选差异表达基因up_genes,down_genes=filter_de_genes(results,p_threshold=0.05,logfc_threshold=0.5)print(f"上调基因数量:{len(up_genes)}")print(f"下调基因数量:{len(down_genes)}")# 显示前10个上调基因print("\n前10个上调基因:")fori,gene_infoinenumerate(up_genes[:10],1):print(f"{i}.{gene_info['gene']}: log_fc={gene_info['log_fc']:.4f}, p={gene_info['p_value']:.2e}")importmatplotlib.pyplotaspltimportseabornassnsdefplot_volcano(results,p_threshold=0.05,logfc_threshold=0.5):""" 绘制火山图 参数: results: 差异表达结果字典 p_threshold: p值阈值 logfc_threshold: log2 fold change阈值 """# 准备数据genes=list(results.keys())log_fcs=[results[gene]['log_fc']forgeneingenes]p_values=[-np.log10(results[gene]['p_value'])forgeneingenes]# 判断基因是否显著colors=[]forgeneingenes:ifresults[gene]['log_fc']>=logfc_thresholdandresults[gene]['p_value']<p_threshold:colors.append('red')# 上调elifresults[gene]['log_fc']<=-logfc_thresholdandresults[gene]['p_value']<p_threshold:colors.append('blue')# 下调else:colors.append('gray')# 不显著# 绘制火山图plt.figure(figsize=(10,6))plt.scatter(log_fcs,p_values,c=colors,alpha=0.5)# 添加阈值线plt.axvline(x=logfc_threshold,color='red',linestyle='--',alpha=0.5)plt.axvline(x=-logfc_threshold,color='blue',linestyle='--',alpha=0.5)plt.axhline(y=-np.log10(p_threshold),color='gray',linestyle='--',alpha=0.5)# 添加标签plt.xlabel('log2 Fold Change')plt.ylabel('-log10(p_value)')plt.title('Volcano Plot')# 添加图例frommatplotlib.linesimportLine2D legend_elements=[Line2D([0],[0],marker='o',color='w',markerfacecolor='red',label='Up-regulated'),Line2D([0],[0],marker='o',color='w',markerfacecolor='blue',label='Down-regulated'),Line2D([0],[0],marker='o',color='w',markerfacecolor='gray',label='Not significant')]plt.legend(handles=legend_elements)plt.tight_layout()plt.show()# 使用示例plot_volcano(results,p_threshold=0.05,logfc_threshold=0.5)defplot_heatmap(data,top_genes,n_samples=10):""" 绘制差异表达基因热图 参数: data: DataFrame格式的表达数据 top_genes: 差异表达基因列表 n_samples: 显示的样本数量 """# 提取top基因的表达数据top_gene_names=[gene['gene']forgeneintop_genes[:20]]heatmap_data=data[top_gene_names].head(n_samples)# 绘制热图plt.figure(figsize=(12,8))sns.heatmap(heatmap_data,cmap='viridis',cbar_kws={'label':'Expression Level'})plt.title('Differentially Expressed Genes Heatmap')plt.xlabel('Genes')plt.ylabel('Samples')plt.tight_layout()plt.show()# 使用示例all_top_genes=up_genes[:10]+down_genes[:10]plot_heatmap(data,all_top_genes,n_samples=20)将上述步骤整合为一个完整的分析流程:
defcomplete_de_analysis_pipeline(h5ad_file,target_cluster):""" 完整的差异表达分析流程 参数: h5ad_file: H5AD格式文件路径 target_cluster: 目标细胞类型名称 返回: results: 差异表达分析结果 up_genes: 上调基因列表 down_genes: 下调基因列表 """# 1. 数据转换print("Step 1: 数据转换...")adata,data=transform_dataframe(h5ad_file)print(f"数据维度:{data.shape}")# 2. 批量差异表达分析print("\nStep 2: 批量差异表达分析...")results=batch_de_analysis(data,target_cluster)print(f"分析基因数量:{len(results)}")# 3. 多重检验校正print("\nStep 3: 多重检验校正...")results=fdr_correction(results)significant_count=sum([1forrinresults.values()ifr.get('significant',False)])print(f"显著基因数量:{significant_count}")# 4. 筛选差异表达基因print("\nStep 4: 筛选差异表达基因...")up_genes,down_genes=filter_de_genes(results,p_threshold=0.05,logfc_threshold=0.5)print(f"上调基因数量:{len(up_genes)}")print(f"下调基因数量:{len(down_genes)}")# 5. 结果可视化print("\nStep 5: 结果可视化...")plot_volcano(results,p_threshold=0.05,logfc_threshold=0.5)all_top_genes=up_genes[:10]+down_genes[:10]plot_heatmap(data,all_top_genes,n_samples=20)returnresults,up_genes,down_genes# 使用示例results,up_genes,down_genes=complete_de_analysis_pipeline("151507.h5ad","Layer1")通过完整分析流程,我们可以获得以下信息:
本文详细介绍了生物信息学中差异表达基因分析的完整流程,包括:
通过这些分析方法,研究人员可以识别在不同条件下表达水平显著不同的基因,为理解生物学过程、疾病机制等提供重要线索。