Pandas groupby 并用新列中的中位数更正
Pandas groupby and correct with median in new column
我的数据框看起来像这样
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 中获取中位数。
我尝试了一些应用和转换功能,但它不起作用。
感谢您的帮助
您可以使用 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
我的数据框看起来像这样
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 中获取中位数。 我尝试了一些应用和转换功能,但它不起作用。 感谢您的帮助
您可以使用 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