【问题标题】:Creating a Pandas column based on values of another column using function使用函数根据另一列的值创建 Pandas 列
【发布时间】:2020-02-13 08:58:57
【问题描述】:

我想根据他们在数据框中的头衔来识别医生,并创建一个新列来表明他们是否是医生,但我的代码很困难。

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)

【问题讨论】:

标签: python pandas function dataframe calculated-columns


【解决方案1】:

要创建带有函数的新列,可以使用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)

【讨论】:

  • 谢谢。如何在多个列中搜索相同的关键字?
猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 2021-03-02
  • 2022-10-15
  • 2018-11-27
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多