pandas groupby并在新列中使用中位数进行校正 [英] Pandas groupby and correct with median in new column

查看:164
本文介绍了 pandas groupby并在新列中使用中位数进行校正的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框看起来像这样

My dataframe look like this

Plate Sample LogRatio
 P1     S1     0.42
 P1     S2     0.23 
 P2     S3     0.41 
 P3     S4     0.36 
 P3     S5     0.18

我已经计算出每个板块的中位数(但也许不是这样开始的最好主意)

I have calculated the median of each plate (but it's probably not the best idea to start like this)

grouped = df.groupby("Plate")
medianesPlate = grouped["LogRatio"].median() 

我想在数据框上添加一列

And I want to add a column on my dataframe

CorrectedLogRatio = LogRatio-median(plate)

我想和:

df["CorrectedLogRatio"] = LogRatio-median(plate)

要拥有这样的东西:

Plate Sample LogRatio CorrectedLogRatio
 P1     S1     0.42    0.42-median(P1)   
 P1     S2     0.23    0.23-median(P1)
 P2     S3     0.41    0.41-median(P2)
 P3     S4     0.36    0.36-median(P3)
 P3     S5     0.18    0.18-median(P3)

但是我不知道如何从medianesPlates获得中位数.我尝试了一些套用和转换功能,但没有用.谢谢您的帮助

But I don't know how to get the median from medianesPlates. I tried some apply and transform functions but it doesn't work. Thanks for any help

推荐答案

您可以使用

You can use transform:

df['CorrectedLogRatio'] = df['LogRatio'] - df.groupby('Plate')['LogRatio'].transform('median')

结果输出:

  Plate Sample  LogRatio  CorrectedLogRatio
0    P1     S1      0.42              0.095
1    P1     S2      0.23             -0.095
2    P2     S3      0.41              0.000
3    P3     S4      0.36              0.090
4    P3     S5      0.18             -0.090

这篇关于 pandas groupby并在新列中使用中位数进行校正的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆