首先,我知道使用正則運算式不是最好的電子郵件驗證,但這是一個初步步驟,稍后會有更好的驗證。
我想創建一個函式來驗證電子郵件地址是否有效,但我不確定如何僅參考資料框中的一列。
import pandas as pd
d=[['Automotive','testgmail.com','bob','smith']]
df=pd.DataFrame(d,columns=['industry','email','first',last])
filename='temp'
我想將代碼保存在 def 函式中,如下所示
def Prospect(colname,errors):
wrong=[]
if #reference to column.str.match(r"^. @. \..{2,}$"):
return
else:
error='this is an invalid email'
wrong.append(error)
return wrong
print(Prospect(errors,colname))
如何創建一個函式以僅參考資料框中的特定列,并僅通過該函式運行該列名并創建一個列印陳述句,說明電子郵件無效?
PS:操作速度不是一個大問題,因為資料集并不龐大。
所需的輸出:
This is an invalid email
uj5u.com熱心網友回復:
我相信你可能想要:
def Prospect(colname, errors, df=df):
m = df[colname].str.match(r"^. @. \..{2,}$")
if m.all():
pass
else:
error='this is an invalid email'
errors.append(error)
errors = []
Prospect('email', errors, df=df)
print(errors)
輸出:['this is an invalid email']
uj5u.com熱心網友回復:
import pandas as pd
import re
d=[['Automotive','testgmail.com','bob','smith'],
['Automotive','[email protected]','bob','smith']]
df=pd.DataFrame(d,columns=['industry','email','first','last'])
email_regex = regex = '^[a-zA-Z0-9.!#$%&’* /=?^_`{|}~-] @[a-zA-Z0-9-] (?:\.[a-zA-Z0-9-] )*$'
df["email"].apply(lambda email: print("This is a valid email: " email if re.search(email_regex,email) else "This is an invalid email: " email))
結果是:
This is an invalid email: testgmail.com
This is a valid email: [email protected]
Process finished with exit code 0
uj5u.com熱心網友回復:
好的,這是我對你的問題的看法(我已經洗掉了“錯誤”論點,直到我明白它應該是/做什么):
import pandas as pd
import re
d=[['Automotive','testgmail.com','bob','smith'],
['Automotive','[email protected]','bob','smith']]
df=pd.DataFrame(d,columns=['industry','email','first','last'])
def Prospect(colname):
email_regex = r"^. @. \..{2,}$"
wrong=[]
for i in range(len(df)):
this_email = df[colname][i]
if re.search(email_regex,this_email):
continue
else:
error=f'{this_email} is an invalid email'
wrong.append(error)
return wrong
print(Prospect('email'))
# ['testgmail.com is an invalid email']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527144.html
標籤:Python熊猫
