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

时间:2020-02-13 08:58:57

标签: python pandas function dataframe calculated-columns

我想根据数据框中的医生名来识别医生,并创建一个新列以表明他们是否是医生,但是我在代码中苦苦挣扎。

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)

1 个答案:

答案 0 :(得分:3)

要使用功能创建新列,可以使用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)

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

doctor_titles = {'Dr', 'dr'}

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