python - 在 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
尝试进行分组和应用来做到这一点,但似乎没有一个能够复制我正在寻找的东西。
解决方案
我们有(在 R 中transform
做同样的事情)(得到 max 和 min 之间的差异)mutate
dplyr
ptp
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
推荐阅读
- mysql - MySQL:如何制作拒绝未成年员工的触发器?
- python - Django过滤器内的条件
- python - 要在 Sagemaker 中使用的 tf.distribute.cluster_resolver.TPUClusterResolver(tpu_name) 的替代方案?
- android - Flutter 应用程序未在任何编辑器上运行
- java - Pivotal/tap 在 brew 上失败
- javascript - querySelectorAll 替代 vuejs nuxtjs
- python - 访问列表中的特定按钮
- react-native - React Native 有条件地设置状态
- javascript - 将 jinja2 模板代码添加到 javascript innerHTML
- c++ - constexpr 使用标准库算法