Python:通过Pandas DataFrame循环以匹配列表中的字符串

时间:2017-07-31 06:51:35

标签: python python-3.x pandas

我的问题是关于Pandas DataFrame和电子邮件地址列表。简化的数据框(称为' df')如下所示:

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

简化的电子邮件地址列表如下所示:

list_of_emails = ['johnsmith@gmail.com', 'judyvolt@hotmail.com', 'bush@yahoo.com']

是否可以遍历数据框,检查姓氏是否是(电子邮件地址的一部分)然后将该电子邮件地址添加到数据框中? 不幸的是,以下代码不起作用,因为第2行我认为:

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

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

通常,您应该考虑仅使用iterrows作为最后的手段。

考虑一下:

import pandas as pd

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

list_of_emails = ['johnsmith@gmail.com', 'judyvolt@hotmail.com', 'bush@yahoo.com']

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   johnsmith@gmail.com
# 1   Volt  judyvolt@hotmail.com
# 2   Bush        bush@yahoo.com

答案 1 :(得分:3)

这是使用apply和lambda函数

的一种方法

For,first match

In [450]: df.Name.apply(
           lambda x: next((e for e in list_of_emails if x.lower() in e), None))
Out[450]:
0     johnsmith@gmail.com
1    judyvolt@hotmail.com
2          bush@yahoo.com
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     [johnsmith@gmail.com]
1    [judyvolt@hotmail.com]
2          [bush@yahoo.com]
Name: Name, dtype: object
相关问题