首页 > 解决方案 > 在 Pandas 中的组内标准化

问题描述

我已经阅读了几个类似的问题,即使问题非常简单,我也无法找到适合我具体尝试的答案。我有一组数据,其中包含分组变量、位置和该位置的值:

Sample    Position    Depth
A         1           2
A         2           3
A         3           4
B         1           1
B         2           3
B         3           2

我想生成一个内部标准化深度的新列,如下所示:

Sample    Position    Depth    NormalizedDepth
A         1           2        0
A         2           3        0.5
A         3           4        1
B         1           1        0
B         2           3        1
B         3           2        0.5

这基本上由公式表示NormalizedDepth = (x - min(x))/(max(x)-min(x)),使得最小值和最大值都属于该组。

我知道如何用以下方法做到这dplyr一点R

depths %>% 
  group_by(Sample) %>%
  mutate(NormalizedDepth = 100 * (Depth - min(Depth))/(max(Depth) - min(Depth)))

我无法弄清楚如何通过pandas尝试进行分组和应用来做到这一点,但似乎没有一个能够复制我正在寻找的东西。

标签: pythonrpandas

解决方案


我们有(在 R 中transform做同样的事情)(得到 max 和 min 之间的差异)mutatedplyrptp

import numpy as np

g=df.groupby('Sample').Depth
df['new']=(df.Depth-g.transform('min'))/g.transform(np.ptp)
0    0.0
1    0.5
2    1.0
3    0.0
4    1.0
5    0.5
Name: Depth, dtype: float64

推荐阅读