Set flag as well as Message in dataframe column using Python

Viewed 73

I have df Like :

      PAN        
0   ACBDV8521N  
1   
2     NaN
3    AWVFEF 

i want df Like this

       PAN           PAN_Status          Invalid
0   ACBDV8521N     Valid PAN Number       False
1                  PAN is not present     True 
2     NaN          PAN is not present     True 
3    AWVFEF        Not Valid PAN          False 

i trying with:

def panValidation(ele):
    if (ele.strip() =='') or pd.isna(ele):
        df['invalid'] = True
        return (True,"PAN is not present")
    elif re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$',ele):
        return "Valid PAN number"
    else:
        return "Not Valid PAN"

but i want also return True/False Flag using Function, if PAN Number is blank/Null then Set True in Invalid column else False

1 Answers

The simpliest is create new column in next step:

df['Invalid'] = df['PAN_Status'] == 'PAN is not present'

If need return tuples in function use:

def panValidation(ele):
    if pd.isna(ele) or (ele.strip() ==''):
        return ("PAN is not present", True)
    elif re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$',ele):
        return ("Valid PAN number", False)
    else:
        return ("Not Valid PAN", False)
    
df[['PAN_Status', 'Invalid']] = df['PAN'].apply(panValidation).tolist()
print (df)
          PAN          PAN_Status  Invalid
0  ACBDV8521N    Valid PAN number    False
1         NaN  PAN is not present     True
2         NaN  PAN is not present     True
3      AWVFEF       Not Valid PAN    False
Related