我有这样的数据框:
**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”列。实际上,我有许多关键字的列表,我保存在字典中,我需要在网址中搜索它,然后提取它以创建新列。
我有这样的字典:
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)
我只得到 bool 值,但我想返回关键字。有什么帮助吗?
最佳答案
想法是使用 if
添加过滤到列表理解的末尾,并添加 next
和 iter
以便在不匹配时返回默认值:
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
如果可能不匹配,也使用 .get
更改第一个 Domain
列解决方案,以使用默认值进行查找:
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
关于python - 当字典的键匹配时如何从列中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640320/