2017-07-31 240 views
0

我的问题是关于Pandas DataFrame和一个电子邮件地址列表。简化的数据框(称为“DF”)是这样的:Python:通过Pandas DataFrame循环以匹配列表中的字符串

Name Address   Email 
0 Bush Apple Street 
1 Volt Orange Street 
2 Smith Kiwi Street 

电子邮件地址的简单列表如下:

list_of_emails = ['[email protected]', '[email protected]', '[email protected]'] 

是否有可能通过数据帧循环,以检查如果姓氏是(部分)电子邮件地址,然后将该电子邮件地址添加到数据框中? 下面的代码不遗憾的是工作,因为2号线的,我认为:

for index, row in df.iterrows(): 
    if row['Name'] in x for x in list_of_emails: 
     df['Email'][index] = x 

你的帮助是非常感谢!

回答

1

通常你应该考虑使用iterrows作为最后的手段而已。

考虑一下:

import pandas as pd 

df = pd.DataFrame({'Name': ['Smith', 'Volt', 'Bush']}) 

list_of_emails = ['[email protected]', '[email protected]', '[email protected]'] 

def foo(name): 
    for email in list_of_emails: 
     if name.lower() in email: 
      return email 

df['Email'] = df['Name'].apply(foo) 

print(df) 

#  Name     Email 
# 0 Smith [email protected] 
# 1 Volt [email protected] 
# 2 Bush  [email protected] 
+0

谢谢@DeepSpace!应用是我正在寻找的功能! – Hoenie

2

下面是使用apply和lambda功能

对于一个方式,第一场比赛

In [450]: df.Name.apply(
      lambda x: next((e for e in list_of_emails if x.lower() in e), None)) 
Out[450]: 
0  [email protected] 
1 [email protected] 
2   [email protected] 
Name: Name, dtype: object 

对于所有比赛,在列表中

In [451]: df.Name.apply(lambda x: [e for e in list_of_emails if x.lower() in e]) 
Out[451]: 
0  [[email protected]] 
1 [[email protected]] 
2   [[email protected]] 
Name: Name, dtype: object