使用函数基于另一列的值创建列

2024-10-04 03:16:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据他们在数据框中的头衔来识别医生,并创建一个新的列来指明他们是否是医生,但我正在努力使用我的代码

doctorcriteria = ['Dr', 'dr']

def doctor(x):
  if doctorcriteria in x:
    return 'Doctor'
  else:
    return 'Not a doctor'

df['doctorcall'] = df.caller_name
df.doctorcall.fillna('Not a doctor', inplace=True)
df.doctorcall = df.doctorcall.apply(doctor)

Tags: 数据代码indfreturnifdefnot
1条回答
网友
1楼 · 发布于 2024-10-04 03:16:22

要使用函数创建新列,可以使用apply

df = pd.DataFrame({'Title':['Dr', 'dr', 'Mr'],
               'Name':['John', 'Jim', 'Jason']})

doctorcriteria = ['Dr', 'dr']

def doctor(x):
    if x.Title in doctorcriteria:
        return 'Doctor'
    else: return 'Not a doctor'

df['IsDoctor'] = df.apply(doctor, axis=1)

但更直接的答案是在Title列上使用map

doctor_titles = {'Dr', 'dr'}

df['IsDoctor'] = df['Title'].map(lambda title: title in doctor_titles)

相关问题 更多 >