【问题标题】:Performing normalization of panda column grouped by values of another column执行按另一列的值分组的熊猫列的规范化
【发布时间】:2021-10-11 13:25:29
【问题描述】:

我想做z-score 规范化,如(link) 所述,基本上由x_normalized = (x- x_mean)/x_std 给出。我有以下数据框

import pandas as pd
  
country = ['US', 'US', 'US', 'UK', 'UK', 'Canada', 'Canada', "Mexico"]
rating =  [0, 2, 1, 4, 3, 1, 0, 1] 

df = pd.DataFrame(list(zip(country,rating)),
               columns =['country', 'rating'])

这是

    country     rating
0   US            0
1   US            2
2   US            1
3   UK            4
4   UK            3
5   Canada        1
6   Canada        0
7   Mexico        1

现在我想对 rating 列的 z-score 归一化,按 country 列的每个不同值分组。那是针对值US 执行值0, 2, 1 的标准化,针对UK4, 3 等等。我该怎么做?

【问题讨论】:

    标签: python pandas pandas-groupby normalization


    【解决方案1】:

    试试groupbytransform

    >>> df.groupby("country")["rating"].transform(lambda x: (x-x.mean())/x.std())
    0   -1.000000
    1    1.000000
    2    0.000000
    3    0.707107
    4   -0.707107
    5    0.707107
    6   -0.707107
    7         NaN
    Name: rating, dtype: float64
    

    【讨论】:

    • 对于Mexico,不应该是0吗?
    • @hi15 - 只有一个观察结果。标准差为 0。除以 0 导致 NaN
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2014-12-12
    • 2022-07-14
    • 2018-10-06
    • 2019-01-29
    • 2020-10-21
    • 2016-03-24
    相关资源
    最近更新 更多