对类使用apply函数

问题描述 投票:0回答:1

我创建了一个函数'salary'。如果薪水少于30000,则返回0;否则,返回0。如果薪水在30000到40000之间,则返回1;否则,如果大于40000,它将返回2。

def salary(x):
    if x < 30000:
        return 0
    elif x >= 30000 and x < 40000:
        return 1
    else:
        return 2

我的数据集“工资”中只有一列。通过应用转换,我创建了一个新列“ salary_level”,该列将保存“ salary”函数中的值。

df['salary_level'] = df['salary'].apply(salary)
df.head()

Output

现在我想使用类来做同样的事情,但是我在此代码上遇到错误:

class Salary():
    def __init__(self,x):
        self.x = x

    def sal(self):
        if self.x < 30000:
            return 0
        elif self.x >= 30000 and self.x < 40000:
            return 1
        else:
            return 2

df['salary_level'] = df.apply(sal)

Error

错误:(““系列”对象没有属性“ x””,“发生在薪水上”)

python pandas function machine-learning
1个回答
0
投票

如果您使用的是Class中的方法,请尝试这种方式:

df['salary_level']= df.apply(lambda x : Salary(x).sal())
© www.soinside.com 2019 - 2024. All rights reserved.