【问题标题】:How to calculate the difference in results between paired rows?如何计算成对行之间的结果差异?
【发布时间】:2017-11-27 21:48:14
【问题描述】:

假设我有以下数据框:

  Sample_Type  test_result
GeneA(normal)    10
 GeneA(tumor)     5
GeneB(normal)     2
 GeneB(tumor)    -6

如何计算Sample_Type 下相同基因的test_result 值之间的差异?

想要的输出是:

              Sample_Type  diff_value
GeneA(normal)-GeneA(tumor)          5
GeneB(normal)-GeneB(tumor)         10 

知道如何解决这个问题吗?

【问题讨论】:

    标签: python-3.x pandas group-by


    【解决方案1】:

    使用groupbyextract

    df.groupby(df.Sample_Type.str.extract('(\w+{5})', expand=False))['test_result'].apply(lambda x: x.iloc[0]-x.iloc[1])
    

    输出:

    Sample_Type
    GeneA    5
    GeneB    8
    Name: test_result, dtype: int64
    

    【讨论】:

    • @MEhsan 不客气。我很欣赏修复解决方案的编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多