【问题标题】:Pandas groupby and correct with median in new columnPandas groupby 并在新列中使用中位数进行更正
【发布时间】:2016-11-10 16:19:26
【问题描述】:

我的数据框是这样的

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

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

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

我想在我的数据框上添加一列

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 中获取中位数。 我尝试了一些应用和转换功能,但它不起作用。 感谢您的帮助

【问题讨论】:

  • 究竟什么不起作用,你得到什么错误?你可能是想使用CorrectedLogRatio = LogRatio-medianesPlate

标签: python pandas dataframe calculated-columns median


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2022-11-23
    • 2022-01-15
    相关资源
    最近更新 更多