【问题标题】:How to use apply function to normalize columns pandas如何使用应用函数来规范化熊猫列
【发布时间】:2021-01-06 17:09:13
【问题描述】:

我需要使用以下公式对列进行规范化:

x/total * 100

我在这里创建了我的自定义函数:

def normalize(df):
    result=[]
    total= df[col].sum()
    for value in df[col]:
        result.append(value/total *100)
    return result

在此处应用该功能。我得到TypeError: normalize() got an unexpected keyword argument 'axis'

df['columnname'].apply(normalize, axis=1)

请问我该怎么做?或者/并且有没有更有效的方法来做到这一点?谢谢

【问题讨论】:

    标签: python python-3.x dataframe apply


    【解决方案1】:

    你需要把 normalize 改为 -

    def normalize(inp):
        inp = inp.values
        result=[]
        
        total= sum(inp)
        for value in inp:
            result.append(value/total *100)
        return result
    
    #### Using Numpy Directly , avoiding the for loop
    def normalize_numpy(inp):
        total= sum(inp)
        return inp/total * 100
    
    >>> l = [100,34,56,71,2,4,5,2,10]
    >>> v = [1,2,3,4,5,68,1,2,3]
    
    >>> df = pd.DataFrame(data=list(zip(l,v)),columns=['Col1','Col2'])
    
    

    多列使用

    >>> df[['Col1','Col2']].apply(lambda x:normalize_numpy(x),axis=0)
            Col1       Col2
    0  35.211268   1.123596
    1  11.971831   2.247191
    2  19.718310   3.370787
    3  25.000000   4.494382
    4   0.704225   5.617978
    5   1.408451  76.404494
    6   1.760563   1.123596
    7   0.704225   2.247191
    8   3.521127   3.370787
    

    单列用法

    >>> df[['Col2']].apply(normalize_numpy,axis=0)
           Value
    0   1.123596
    1   2.247191
    2   3.370787
    3   4.494382
    4   5.617978
    5  76.404494
    6   1.123596
    7   2.247191
    8   3.370787
    

    【讨论】:

    • 如果我还需要将其扩展到多列?
    • 修改答案以适应单列和多列使用
    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2014-12-12
    • 2020-02-10
    • 1970-01-01
    • 2020-10-21
    • 2015-10-24
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多