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

标签 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”列。实际上,我有许多关键字的列表,我保存在字典中,我需要在网址中搜索它,然后提取它以创建新列。

我有这样的字典:

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 添加过滤到列表理解的末尾,并添加 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

如果可能不匹配,也使用 .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/

相关文章:

python - 如何将图像的 HH 子带传递给 greycomatrix 函数?

python - 更改Python中的包导入名称

python - 在 Heroku 上找不到 parse_rest 模块,但在 localhost 上工作

python - Pandas 合并_asof : ambiguous argument types error

具有 2 个数据帧的 Python lambda 函数

sockets - 在ASIO Reactor中使用Lambda的Auto vs Typedef

python - 在 zsh 终端的 Mac 上的 Python 中安装 xgboost 失败

pandas - 从 Pandas 数据帧覆盖 seaborn 中的两个热图(一个是围绕另一个单元格的框架)

python - 无法控制 df.plot() 上第二个 y 轴的比例

c# - 空 linq 查询的返回值