Pandas按条件分组计数

2024-09-30 20:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

示例数据

给定以下数据帧:

| feature | gene  |  target  | pos | 
| 1_1_1   | NRAS  |  AATTGG  | 60  |
| 1_1_1   | NRAS  |  TTGGCC  | 6   |
| 1_1_1   | NRAS  |  AATTGG  | 20  |
| 1_1_1   | KRAS  |  GGGGTT  |  0  |
| 1_1_1   | KRAS  |  GGGGTT  |  0  |
| 1_1_1   | KRAS  |  GGGGTT  |  0  |
| 1_1_2   | NRAS  |  CCTTAA  | 2   |
| 1_1_2   | NRAS  |  GGAATT  | 8   |
| 1_1_2   | NRAS  |  AATTGG  | 60  |

问题

对于每一个特征,我想用以下规则计算每个基因中出现了多少个靶点:

  • 如果一个目标只出现在每个基因的一个位置(pos列),那么每次看到它都会得到1的计数
  • 如果同一个目标出现在每个基因的多个位置,它将得到一个计数(count at position/total positions found)
  • 总结每个特征每个基因的总数

到目前为止我所做的一切

^{pr2}$

这给了我一个数据帧,其中出现在多个位置的目标被标记为true。现在我只需要弄清楚如何使计数正常化。在

期望输出

| feature | gene  |  count
| 1_1_1   | NRAS  |   2
| 1_1_1   | KRAS  |   1
| 1_1_2   | NRAS  |   3

所以在上面的例子中,对于1u1nras,AATTGG在位置60和位置20都可以找到,每一个都会得到0.5的计数。因为TTGGCC在一个位置被找到一次,所以它的计数是1。这总共是2。在

如果在同一位置发现了3次NRAS TTGGCC,则每一次的计数为1,总计为3+。5+。5=4。在

解决方案需要检查出现在不同位置的同一目标,然后相应地调整计数,这是我很难处理的部分。我的最终目标是选择每个组中计数最高的基因。在


Tags: 数据pos示例目标count基因特征feature
2条回答

我不太清楚为什么第一排的计数应该是2。你能试着绕过这个问题吗:

import pandas as pd
feature = ["1_1_1"]*6 +["1_1_2"]*3
gene = ["NRAS"]*3+["KRAS"]*3+["NRAS"]*3
target = ["AATTGG","TTGGCC", "AATTGG"]+ ["GGGGTT"]*3 + ["CCTTAA", "GGGGTT", "AATTGG"]
pos = [60,6,20,0,0,0,2,8,60]
df = pd.DataFrame({"feature":feature,
                   "gene":gene,
                   "target":target,
                   "pos":pos})

df.groupby(["feature", "gene"])\
  .apply(lambda x:len(x.drop_duplicates(["target", "pos"])))

好吧,我想好了。如果有更有效的方法来做这件事,我洗耳恭听!在

    # flag targets that are multi-mapped and add flag as new column
    matches['multi_mapped'] = np.where(matches.groupby(["FeatureID", "gene", "target"]).pos.transform('nunique') > 1, "T", '')

    # separate multi and non multi mapped reads using flag
    non = matches[matches["multi_mapped"] != "T"]\
        .drop("multi_mapped", axis=1)
    multi = matches[matches["multi_mapped"] == "T"]\
        .drop("multi_mapped", axis=1)

    # add counts to non multi mapped reads
    non = non.groupby(["FeatureID", "gene", "target"])\
        .count().reset_index().rename(columns={"pos":"count"})

    # add counts to multi-mapped reads with normaliztion 
    multi["count"] = multi.groupby(["FeatureID", "gene", "target"])\
          .transform(lambda x: 1/x.count())
    multi.drop("pos", axis=1, inplace=True)

    # join the multi and non back together
    counts = pd.concat([multi, non], axis=0)

相关问题 更多 >