我有这样的dataframe:

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

它只是一个假想的数据。我具有要在其中使用"Domain"和"URL“列的clickstream数据。实际上,我有许多保存在字典中的关键字的列表,我需要在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)

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

分析解答

想法是将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