首页 > 解决方案 > 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也无法正常工作。

非常感谢任何建议

标签: pythonexcelpandasnumpyif-statement

解决方案


尝试这个:

# 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'])

推荐阅读