使用 IF 语句的 Python 用户定义函数不起作用

标签 python pandas function lambda

我有以下数据框

Index   education   marital-status  occupation         gender    target
0       bachelors   never-married   adm-clerical       male      0
1       bachelors   spouse          exec-managerial    male      0
2       hs-grad     divorced        handlers-cleaners  male      0
3       11th        spouse          handlers-cleaners  male      0
4       bachelors   spouse          prof-specialty     female    0
5       masters     spouse          exec-managerial    female    0
6       other       other           other-service      female    0
7       hs-grad     spouse          exec-managerial    male      1
8       masters     never-married   prof-specialty     female    1
9       bachelors   spouse          exec-managerial    male      1

有人可以向我解释为什么以下内容不起作用 - 从我阅读的内容和我所看到的应用来看,我觉得应该是这样。

def new_features(education, gender, target):

  if [((education == 'bachelors') & (gender == 'male') & (target == 1))]:
      result = 'educated_male_convert'
  elif [((education == 'bachelors') & (gender == 'female') & (target == 1))]:
      result = 'educated_female_convert'
  else:
      result = 'educated_not_determined'
  return result

df['new_col'] = df.apply(lambda row: new_features(row['education'], row['gender'], row['target']), axis=1)

它只是返回:educated_male_convert

我遵循了大量教程并阅读了其他线程并将相同的代码应用于我自己的数据集 - 不确定我遗漏了什么。

任何帮助将不胜感激

最佳答案

问题是您将 if 条件放在方括号中。因此,代码不是测试表达式 if False: ...,而是实际测试 if [False]: ...。由于任何非空列表的计算结果为 True,因此 [False] 将被计算为 True,并且代码会转到错误的分支。

关于使用 IF 语句的 Python 用户定义函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643368/

相关文章:

Python 多处理控制的双向队列

pandas - 获取列表 azure synapse 工作区中 data Lake gen2 文件夹的所有内容

c++ - 用boost c++重新绑定(bind)类成员函数

python - 每个位置参数的可选参数

Python Pandas : Append Dataframe To Another Dataframe Only If Column Value is Unique

python - pandas shift 将我的列从整数转换为 float 。

arrays - 在 bash 函数中定义一个本地数组并在该函数外部访问它

mysql - 使用函数: The used SELECT statements have a different number of columns时出错

python - 在 Python 中绘制 Pandas 数据集的树形图

python - 使用 numpy 进行数组重分类