Python 从Dataframe的逻辑创建函数
我有过这样的经历Python 从Dataframe的逻辑创建函数,python,regex,pandas,function,Python,Regex,Pandas,Function,我有过这样的经历 Name PAN 0 x BBDFW7894Q 1 s 2 A QWE7892E 我想在确认PAN号码后再这样做 Name PAN PAN_Status 0 x BBDFW7894Q Valid PAN number 1 s PAN is not present 2 A
Name PAN
0 x BBDFW7894Q
1 s
2 A QWE7892E
我想在确认PAN号码后再这样做
Name PAN PAN_Status
0 x BBDFW7894Q Valid PAN number
1 s PAN is not present
2 A QWE7892E Invalid PAN number
我试图用下面的逻辑
df["PAN_Status"] = ["Valid PAN number" if re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$',ele)\
else ("PAN is not present"if ele==' ' else "Not Valid PAN") for ele in
但是我想为这个使用一个函数,第二个条件是测试缺失值或emty字符串:
m1 = df["PAN"].str.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$', na=False)
m2 = df["PAN"].str.strip().eq('') | df['PAN'].isna()
df["PAN_Status"] = np.select([m1, m2],
['Valid PAN number','PAN is not present'],
'Not Valid PAN')
具有功能的解决方案:
def test(ele):
if (ele.strip() =='') or pd.isna(ele):
return "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"
df["PAN_Status"] = df["PAN"].apply(test)
print (df)
Name PAN PAN_Status
0 x BBDFW7894Q Valid PAN number
1 s NaN PAN is not present
2 A QWE7892E Not Valid PAN
先生,你总是对的,但是,我想要一个像'def():code return'@user14784453-Done这样的函数。如果我的回答有帮助,别忘了。谢谢。@user14784453-若要将答案标记为已接受,请单击答案旁边的复选标记,将其从空心切换为绿色()。非常感谢。