Python 3.x 如何计算成对行之间的结果差异?

Python 3.x 如何计算成对行之间的结果差异?,python-3.x,pandas,group-by,Python 3.x,Pandas,Group By,假设我有以下数据帧: Sample_Type test_result GeneA(normal) 10 GeneA(tumor) 5 GeneB(normal) 2 GeneB(tumor) -6 如何计算样本类型下相同基因的测试结果值之间的差异 所需输出为: Sample_Type diff_value GeneA(normal)-GeneA(tumor) 5 GeneB(normal)-GeneB(tum

假设我有以下数据帧:

  Sample_Type  test_result
GeneA(normal)    10
 GeneA(tumor)     5
GeneB(normal)     2
 GeneB(tumor)    -6
如何计算
样本类型下相同基因的
测试结果
值之间的差异

所需输出为:

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

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

使用
groupby
extract

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

@梅森,不客气。我非常感谢您对解决方案的修改。