You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计每行特定基因出现次数并生成表格以计算基因丰度

解决方案

核心思路

针对你的需求,我们需要先按样本去重统计目标基因的出现样本数(避免同一样本内重复基因干扰),再计算丰度,最后生成统计表格并绘制柱状图。

代码实现(Python + Pandas)

1. 导入依赖库

import pandas as pd
import matplotlib.pyplot as plt

2. 加载并预处理数据

# 替换为你的Excel文件路径
df = pd.read_excel("你的基因数据.xlsx")
# 提取所有存储基因的列(从"AMR genotypes"到最后一列)
gene_columns = df.columns[df.columns.get_loc("AMR genotypes"):]

3. 定义目标基因列表

# 替换为你需要统计的基因列表Y
target_genes = ["fosX", "vga(G)", "geneC", "geneD"]

4. 统计每个基因的出现样本数

# 初始化统计字典
gene_sample_counter = {gene: 0 for gene in target_genes}

# 遍历每个样本,去重后检查基因存在性
for _, row in df.iterrows():
    # 提取当前样本的非空基因并去重
    unique_genes_in_sample = set(row[gene_columns].dropna())
    # 对每个目标基因,若存在则计数+1
    for gene in target_genes:
        if gene in unique_genes_in_sample:
            gene_sample_counter[gene] += 1

5. 生成统计表格并计算丰度

# 转换为DataFrame格式
result_df = pd.DataFrame.from_dict(
    gene_sample_counter,
    orient="index",
    columns=["出现样本数"]
).reset_index().rename(columns={"index": "基因名称"})

# 计算丰度:出现样本数 / 总样本数
total_samples = len(df)
result_df["丰度"] = result_df["出现样本数"] / total_samples

# 查看结果
print(result_df)

6. 绘制丰度柱状图

plt.figure(figsize=(10, 6))
plt.bar(result_df["基因名称"], result_df["丰度"], color="#4285F4")
plt.title("目标基因丰度分布")
plt.xlabel("基因名称")
plt.ylabel("丰度(出现样本数/总样本数)")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
plt.show()

补充说明

  • 上述代码默认同一样本内的重复基因只计1次,符合你避免重复干扰的需求;如果需要统计基因的总出现次数(含同一样本重复),只需把set(row[gene_columns].dropna())改为row[gene_columns].dropna().tolist(),并把计数逻辑改为gene_sample_counter[gene] += row[gene_columns].value_counts().get(gene, 0)。
  • 针对18000+样本的大数据量,可改用更高效的向量化操作替代循环:
# 向量化统计(更高效)
gene_presence = df[gene_columns].apply(lambda x: x.dropna().unique(), axis=1)
for gene in target_genes:
    gene_sample_counter[gene] = gene_presence.apply(lambda x: gene in x).sum()

内容的提问来源于stack exchange,提问作者Dragoran21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 09:03:14