python - python中的嵌套if公式
问题描述
我正在尝试在 pandas 中执行嵌套 if(连同 AND & OR 函数),我有以下两个数据框
dF1
TR_ID C_ID Code Check1 Check2
1 101 P1 N Y
2 102 P2 Y Y
3 103 P3 N Y
4 104 P4 Y N
5 105 P5 N N
6 106 P6 Y Y
7 107 P7 N N
8 108 P8 N N
9 109 P9 Y Y
10 110 P10 Y N
dF2
C_ID CC
101 A1
102 A2
103 A3
104 A4
105 A5
106 A6
107 A7
108 A8
109 A9
110 A10
我正在尝试Df1
使用以下 excel 公式创建一个新列“结果”,我对 Pandas Python 中的编码相当陌生,
Excel 公式 =
IF(AND(OR($D2="P2",$D2="P4",$D2="P6",$D2="P9"),$E2="Y",$F2="Y"),"A11",VLOOKUP($C2,$J$2:$K$11,2,0))'
生成的数据框应如下所示
TR_ID C_ID Code Check1 Check2 RESULT
1 101 P1 N Y A1
2 102 P2 Y Y A11
3 103 P3 N Y A3
4 104 P4 Y N A4
5 105 P5 N N A5
6 106 P6 Y Y A11
7 107 P7 N N A7
8 108 P8 N N A8
9 109 P9 Y Y A11
10 110 P10 Y N A10
我正在python中尝试这段代码df1['CC'] = df1['Code'].apply(lambda x: 'A11' if x in ('P2','P4','P6','P9') else 'N')
但我无法合并 check1 和 Check2 标准,否则vlookup
也无法正常工作。
非常感谢任何建议
解决方案
尝试这个:
# This is the first part of your IF statement
cond = (
df1['Code'].isin(['P2', 'P4', 'P6', 'P9'])
& df1['Check1'].eq('Y')
& df1['Check2'].eq('Y')
)
# And the VLOOKUP
# (but don't name your dataframe `vlookup` in production code please
vlookup = df1[['C_ID']].merge(df2, on='C_ID')
# Combining the two
df1['RESULT'] = np.where(cond, 'All', vlookup['CC'])
推荐阅读
- python - 使用熊猫从我的数据集中删除特定行
- ios - 滚动视图动画时获取偏移量
- javascript - 如何让 useEffect 监听 localStorage 的任何变化?
- excel - 在查找公式 VBA 中使用变量名
- javascript - 当我在 Vue.js 中使用作用域 css 时,“this”在模板中变得未定义
- css - 如何解决在角度材料的多选中选择所有值的问题?
- android - 在android中重命名文件
- python - 如何在人脸识别的KNN算法中获取匹配图像的百分比
- node.js - 如何确保一个异步功能在另一个异步功能在 NodeJS 中启动之前完成?
- sql - 使用 UUID 列设置大查询表?