当字典的键匹配时如何从列中提取字符串

时间:2019-10-31 09:32:56

标签: python pandas lambda apply

我有这样的数据框:

**Domain**         **URL**  
Amazon         amazon.com/xyz/butter
Amazon         amazon.com/xyz/orange
Facebook       facebook.com/male
Google         google.com/airport
Google         goolge.com/car

它只是一个假想的数据。我在其中要使用“域”和“ URL”列的点击流数据。实际上,我有许多保存在词典中的关键字的列表,我需要在url中搜索它,然后将其提取以创建新列。

我有这样的字典:

dict_keyword = {'Facebook': ['boy', 'girl', 'man'], 'Google': ['airport', 'car', 'konfigurator'], 'Amazon': ['apple', 'orange', 'butter']

我想获得这样的输出:

  **Domain**         **URL**                     Keyword
    Amazon         amazon.com/xyz/butter         butter
    Amazon         amazon.com/xyz/orange         orange
    Facebook       facebook.com/male             male
    Google         google.com/airport            airport
    Google         goolge.com/car                car

到目前为止,我只想用一行代码来做。我正在尝试使用

df['Keyword'] = df.apply(lambda x: any(substring in x.URL for substring in dict_config[x.Domain]) ,axis =1)

我仅获得布尔值,但我想返回关键字。有帮助吗?

1 个答案:

答案 0 :(得分:1)

想法是将带有if的过滤条件添加到列表理解的末尾,并且如果没有匹配项,还将nextiter添加为返回默认值:

f = lambda x: next(iter([sub for sub in dict_config[x.Domain] if sub in x.URL]), 'no match')
df['Keyword'] = df.apply(f, axis=1)
print (df)
     Domain                    URL   Keyword
0    Amazon  amazon.com/xyz/butter    butter
1    Amazon  amazon.com/xyz/orange    orange
2  Facebook      facebook.com/male  no match
3    Google     google.com/airport   airport
4    Google         goolge.com/car       car

如果可能也无法匹配,则将第一Domain列解决方案更改为.get,以使用默认值进行查找:

print (df)
     Domain                    URL
0    Amazon  amazon.com/xyz/butter
1    Amazon  amazon.com/xyz/orange
2  Facebook      facebook.com/male
3    Google     google.com/airport
4   Google1         goolge.com/car <- changed last value to Google1

dict_config = {'Facebook': ['boy', 'girl', 'man'], 
               'Google': ['airport', 'car', 'konfigurator'],
               'Amazon': ['apple', 'orange', 'butter']}

f = lambda x: next(iter([sub for sub in dict_config.get(x.Domain, '') 
                         if sub in x.URL]), 'no match')
df['Keyword'] = df.apply(f, axis=1)
     Domain                    URL   Keyword
0    Amazon  amazon.com/xyz/butter    butter
1    Amazon  amazon.com/xyz/orange    orange
2  Facebook      facebook.com/male  no match
3    Google     google.com/airport   airport
4   Google1         goolge.com/car  no match