微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从数据框中提取与列表进行比较的字符串

如何解决从数据框中提取与列表进行比较的字符串

你可以用extractjoin在所有值List通过|什么手段orregex

List1 = ['Three has' , 'Mail' , 'Done' , 'Game' , 'Time has come']
df['Col 3'] = df['Col 2'].str.extract("(" + "|".join(List1) +")", expand=False)
print (df)
   Col 1           Col 2      Col 3
0      1        The date        NaN
1      2  Three has come  Three has
2      3       Mail Sent       Mail
3      4       Done Deal       Done

一个解决方案:

List1 = ['Three has' , 'Mail' , 'Done' , 'Game' , 'Time has come']

df['Col 3'] = df['Col 2'].apply(lambda x: ''.join([L for L in List1 if L in x]))
df['Col 3'] = df['Col 3'].mask(df['Col 3'] == '')
print (df)
   Col 1           Col 2      Col 3
0      1        The date        NaN
1      2  Three has come  Three has
2      3       Mail Sent       Mail
3      4       Done Deal       Done

解决方法

我正在尝试从pandas数据帧中的DF中提取字符串,并且源字符串在必须与之匹配的列表中。我尝试使用adf.str.extract(list1)但我收到了无法哈希类型的错误,我想我将列表与DF比较的方式不正确

Col 1   Col 2
1       The date
2       Three has come
3       Mail Sent
4       Done Deal

Col 1   Col 2           Col 3 
1       The date        NaN
2       Three has come  Three has
3       Mail Sent        Mail
4       Done Deal        Done

我的清单如下

List1 = ['Three has','Mail','Done','Game','Time has come']

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。