python - Groupby 和基于特定行值的计算

标签 python pandas dataframe pandas-groupby

我有看起来像这样的数据:

d = {'id' : [1, 1, 1, 2, 2, 2],
     'levels': ['low', 'perfect', 'high', 'low', 'perfect', 'high'],
     'value': [1, 10, 13, 2, 10, 13]}

df = pd.DataFrame(d, columns=['id', 'levels', 'value'])
df = df.groupby(['id','levels'])[['value']].mean()
对于每个 [id, levels],我想找到 value 之间的差异行和 valueperfect排。它看起来像这样:
id | levels | value | penalty
1  | high   | 13    | 3
   | low    | 1     | 9
   | perfect| 10    | 0
2  | high   | 13    | 3
   | low    | 2     | 8
   | perfect| 10    | 0
例如,在第一行中,您将从完美值 10 中减去 13,得到 3。
那么如何在找到 perfect 的地方进行计算?每个值 [id, levels] ,然后找出差异?

最佳答案

使用 xs 选择数据框的横截面,然后从 level=0 上的给定数据帧中减去该横截面

df['penalty'] =  df['value'].sub(df['value'].xs('perfect', level=1)).abs()
            value  penalty
id levels                 
1  high        13        3
   low          1        9
   perfect     10        0
2  high        13        3
   low          2        8
   perfect     10        0

关于python - Groupby 和基于特定行值的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67662242/

相关文章:

python-3.x - 根据列将多个无标题列中的值替换为 0、1、2

python - pandas groupby.agg 列出行为

python - Pandas groupby 应用执行缓慢

python - 如何将本地目录包含到 Sphinx 文档中?

python - 如何对存储在 pandas DataFrame 中的数据执行 t 检验

pandas - 根据条件从另一个数据框中复制列值

python - "ValueError: Length of values does not match length of index"尝试修改 pandas groupby 的列值时

python - HttpsCallable 从 python 返回

python - 在 Python : is there something like -0? 中对列表进行切片

python - 将日期时间索引值转换为索引号