在python中创建一个新列并使用多个numpy“where”条件赋值

2024-04-30 03:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我几乎没有什么工作条件,比如:

1. if employment is 'salaried' or 'business' and annual income is '<=10 lakhs' and stp flagging is 'NON STP' then result should be 'No Issue'
2. if employment is 'salaried' or 'business' and annual income is '>10 lakhs' and stp flagging is 'STP' then result should be 'No Issue'
3. if employment is 'salaried' or 'business' and annual income is '>10 lakhs' and stp flagging is 'NON STP' then result should be 'Issue'
4. if employment is 'salaried' or 'business' and annual income is '<=10 lakhs' and stp flagging is 'STP' then result should be 'Issue'

我试过这个密码-

df['Result'] = 'Null'
df['Result']=np.where((df['Employment']=='Salaried')|
                      (df['Employment']=='Business')&
                      (df['Annual income of policy owner']=='<= 10 lakh')&
                      (df['STP flagging'] == 'NON STP'),'No Issue','')

df['Result']=np.where((df['Employment']=='Salaried')|
                      (df['Employment']=='Business')&
                      (df['Annual income of policy owner']=='>10 lakh')&
                      (df['STP flagging'] == 'STP'),'No Issue','')

df['Result']=np.where((df['Employment']=='Salaried')|
                      (df['Employment']=='Business')&
                      (df['Annual income of policy owner']=='>10 lakh')&
                      (df['STP flagging'] == 'NON STP'),'Issue','')

df['Result']=np.where((df['Employment']=='Salaried')|
                      (df['Employment']=='Business')&
                      (df['Annual income of policy owner']=='<= 10 lakh')&
                      (df['STP flagging'] == 'STP'),'Issue','')

但只有最后一行有效,我需要为每个条件指定结果。请帮我修改代码


Tags: oranddfifisissueresultbusiness
1条回答
网友
1楼 · 发布于 2024-04-30 03:21:58

我认为您没有明确定义您的要求/条件。您可以使用numpy.where尝试以下内容:

# Import package
import numpy as np

# Conditions
sb = (df['Employment'] == 'Salaried') | (df['Annual income of policy owner'] == 'Business Owner')
non_stop = (df['STP flagging'] == 'NON STP')
stop = (df['STP flagging'] == 'STP')
lakhs = df['Annual income of policy owner']

# Assignment
df['result'] = np.where(sb & stop & (lakhs.eq('>10 lakh')),'No Issue',
                        np.where(sb & non_stop & (lakhs.eq('<=10 lakh')),"No issue",
                        np.where(sb & non_stop & (lakhs.eq('>10 lakh')),"Issue",
                        np.where(sb & stop & (lakhs.eq('<= 10 lakh')),"Issue","No condition"))))

# Print new column values
>>> df['result'].value_counts()

No condition    5618
Issue           1264
No Issue         618
Name: result, dtype: int64

相关问题 更多 >