如何在pandas中定义用户定义的函数

时间:2016-02-15 16:34:26

标签: python pandas

我有一个包含

等信息的csv文件
name    salary  department
a        2500      x
b        5000      y
c        10000      y
d        20000      x 

我需要使用Pandas将其转换为类似

的形式
dept    name    position
x        a       Normal Employee
x        b       Normal Employee
y        c       Experienced Employee
y        d       Experienced Employee

如果薪水< = 8000职位是普通员工

如果工资> 8000&& < = 25000职位是有经验的员工

我的默认代码

import csv
import pandas
pandas.set_option('display.max_rows', 999)
data_df = pandas.read_csv('employeedetails.csv')
#print(data_df.columns)
t = data_df.groupby(['dept'])
print t

我需要在此代码中进行哪些更改才能获得上面提到的输出

3 个答案:

答案 0 :(得分:6)

您可以定义2个面具并将其传递给np.where

In [91]:
normal = df['salary'] <= 8000
experienced = (df['salary'] > 8000) & (df['salary'] <= 25000)
df['position'] = np.where(normal, 'normal emplyee', np.where(experienced, 'experienced employee', 'unknown'))
df

Out[91]:
  name  salary department              position
0    a    2500          x        normal emplyee
1    b    5000          y        normal emplyee
2    c   10000          y  experienced employee
3    d   20000          x  experienced employee

或稍微更具可读性是将它们传递给loc

In [92]:
df.loc[normal, 'position'] = 'normal employee'
df.loc[experienced,'position'] = 'experienced employee'
df

Out[92]:
  name  salary department              position
0    a    2500          x       normal employee
1    b    5000          y       normal employee
2    c   10000          y  experienced employee
3    d   20000          x  experienced employee

答案 1 :(得分:3)

我会使用一个简单的函数:

def f(x):
    if x <= 8000:
        x = 'Normal Employee'
    elif 8000 < x <= 25000:
        x = 'Experienced Employee'
    return x

然后将其应用于df

df['position'] = df['salary'].apply(f)

答案 2 :(得分:2)

有用的功能是apply

data_df['position'] = data_df['salary'].apply(lambda salary: 'Normal Employee' if salary <= 8000 else 'Experienced Employee', axis=1)

这会将lambda函数应用于薪水列中的每个元素。