基于多列条件映射到数据框

Conditional mapping to a dataframe based on multiple columns

我有一个数据框,我需要在其中根据基于值的条件在两个单独的列上映射类别。执行此操作的总行数约为一百万。

示例数据框是:

df = pd.DataFrame({'col1':['B','A','A','B','C','B','C','C','A'],
               'col2':[10,30,40,20,60,30,70,80,50]})

现在,True 的条件是:

  1. 一个:>30
  2. 乙:>20
  3. 摄氏度:>60

如果 col2 中的值符合上述条件,则结果为 True(1),否则为 False(0)。

预期结果是:

    col1    col2    result
0   B   10  0
1   A   30  0
2   A   40  1
3   B   20  1
4   C   60  0
5   B   30  1
6   C   70  1
7   C   80  1
8   A   50  1

我尝试按照以下方式执行此操作:

df['result'] = np.select([(df['col1']=='A') & (df['col2']>30),
                      (df['col1']=='A') & (df['col2']<=30),
                      (df['col1']=='B') & (df['col2']>10),
                      (df['col1']=='B') & (df['col2']<=10),
                      (df['col1']=='C') & (df['col2']>60),
                      (df['col1']=='C') & (df['col2']<=60),
                     ],
                     [True,
                      False,
                      True,
                      False,
                      True,
                      False
                     ]
                    )

但是,我不知道这是否是执行此操作的最佳方法。欢迎其他答案。

您可以按位 | 链接掩码 OR:

df['result'] = (df['col1']=='A') & (df['col2']>30) |
               (df['col1']=='B') & (df['col2']>10) | 
               (df['col1']=='C') & (df['col2']>60)

或者:

df['result'] = np.where((df['col1']=='A') & (df['col2']>30) |
                        (df['col1']=='B') & (df['col2']>10) | 
                        (df['col1']=='C') & (df['col2']>60), 1, 0)