如何解决用通讯员姓名映射字符
我有以下数据框:
strings. intention
g google
go google
yo youtube
y youtube
a amazon
am amazon
skys skype
我想做的是用字符串映射字符,所以如果我在第一行有“g”并且意图是谷歌那么它匹配但是,最后一行是“天空”和意图是skype,第4个字符不匹配,则为false。
我正在寻找的最终结果是:
strings. intention match
g google TRUE
go google TRUE
yo youtube TRUE
y youtube TRUE
a amazon TRUE
am amazon TRUE
skys skype FALSE
到目前为止我尝试的是这个,它有效但不完全,因为有一些例子我有字符串“ne”并且它应该显示netflix但它显示例如“nykaa”。有没有更好的方法来做到这一点?
keywords = dict(zip(df.string,df['intent_pretty_name']))
df['match'] = [next((keywords[y] for y in x.split() if y in keywords),None) for x in df['strings']]
谢谢
解决方法
您可以使用简单的 string.startswith
#for corresponding string and intention
match = intention.startswith(string) #returns true or false
参考:
,如果您不介意 apply
(在大型数据集上可能会很慢),您可以这样做 startswith
:
df['match'] = df.apply(lambda s: s['intention'].startswith(s['strings']),axis=1)
df
Out[139]:
strings intention match
0 g google True
1 go google True
2 yo youtube True
3 y youtube True
4 a amazon True
5 am amazon True
6 skys skype False
,
对于矢量化解决方案,您可以将 pd.Series.replace(...)
与 regex=True
结合使用:
df["match"] = df["intention"].replace(df["strings"]+".*","True",regex=True).eq("True")
输出:
strings intention match
0 g google True
1 go google True
2 yo youtube True
3 y youtube True
4 a amazon True
5 am amazon True
6 skys skype False
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。