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

Edw*_*aby 6 python pandas

我有一个包含类似信息的csv文件

name    salary  department
a        2500      x
b        5000      y
c        10000      y
d        20000      x 
Run Code Online (Sandbox Code Playgroud)

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

dept    name    position
x        a       Normal Employee
x        b       Normal Employee
y        c       Experienced Employee
y        d       Experienced Employee
Run Code Online (Sandbox Code Playgroud)

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

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

我的默认代码为group by

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
Run Code Online (Sandbox Code Playgroud)

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

EdC*_*ica 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
Run Code Online (Sandbox Code Playgroud)

或稍微更具可读性是将它们传递给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
Run Code Online (Sandbox Code Playgroud)


Fab*_*nna 6

我将使用一个简单的函数,例如:

def f(x):
    if x <= 8000:
        x = 'Normal Employee'
    elif 8000 < x <= 25000:
        x = 'Experienced Employee'
    return x
Run Code Online (Sandbox Code Playgroud)

然后将其应用于df

df['position'] = df['salary'].apply(f)
Run Code Online (Sandbox Code Playgroud)