Python:如果在熊猫数据框中满足多个条件的条件,则插入一行

时间:2020-09-22 11:45:41

标签: python pandas dataframe

所以我有如下数据框:

Id     a_no    desc       flag_1    flag_2 
100     20     test         1         0
100     25     new_test     1         1
110     25     new_test     0         1

现在,我尝试使用以下逻辑添加两列msgfinal_flag

if len(desc) < 5, then msg = 'Short length' and final_flag = 'Reject'
if flag_1 == 0, then msg = 'Missing_item' and final_flag = 'Error'
if flag_2 == 0, then msg = 'Find_item' and final_flag = 'Error'

为了达到上述目的,我正在尝试下面的代码

df['msg'] = np.where(df['desc'].str.len() < 5,'Short length',\
            np.where(df['flag_1']==0,'Missing_item',\
            np.where(df['flag_2']==0,'Find_item','All is Good')))
df['final_flag'] = np.where(df['msg'].str.contains('Missing | Find',regex=True),'Error',np.where(df['msg'].str.contains('Good',regex=True),'Accepted','Reject'))

使用上面的代码,我没有得到期望的输出,如下所示:

Id     a_no    desc       flag_1    flag_2      msg             final_flag
100     20     test         1         0     'Short length'         Reject
100     20     test         1         0     'Find Item'            Error <--as flag_2 ==0 
100     25     new_test     1         1     'All is Good'          Accepted
110     25     new_test     0         1     'Missing Item'         Error

即对于每个条件(或如上所述的逻辑),如果满足条件,则在最终数据帧中插入一行。

我可以看到我的代码段不够。

我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

所以我已经制定出类似以下的内容:

# creating a column based on each logic#
df['msg_str'] = np.where(df['desc'].str.len() < 5, 'Short Length','')
df['msg_flag_1'] = np.where(df['flag_1']==0,'Missing Item','')
df['msg_flag_2'] = np.where(df['flag_2']==0,'Find Item','')
#Unpivoting the dataframe
df_melt = pd.melt(df,id_vars = ['msg_str','msg_flag_1','msg_flag_2'],value_name='msg')

以上技术应产生如下数据帧:

Id    a_no      variable      msg
100    20       msg_str      Short Length
100    20       msg_flag_1   
100    20       msg_flag_2   Find Item
100    25       msg_str      
100    25       msg_flag_1   
100    25       msg_flag_2  
110    25       msg_str     
110    25       msg_str_1    Missing Item
110    25       msg_str_2      

现在我添加另一个col:

df_melt['status'] = np.where(df_melt['msg'].str.contains('Missing|Short|Find',regex=True),'Reject','Accept')

这实际上解决了问题。当然,我可以再次旋转上面的df以获得所需的输出。

答案 1 :(得分:-1)

您也可以使用Apply功能:

dt['msg'] =''
dt['final_flag']=''
def replace_dt(x):
    if len(x['desc'])<5: 
        x.loc['msg','final_flag']=['Short length','Reject']
    if x['flag_1']==0:
        x.loc['msg','final_flag']=['Missing_item','Error']
    if x['flag_2']==0:
       x.loc['msg','final_flag']=['Find_item','Error']
    return x
dt.apply(replace_dt,axis = 1 )