python - 如何删除以python中的某个字符串结尾的数据框中的某些列表成员
问题描述
如何删除以python中某个字符串结尾的数据框中的某些列表成员?例如我有这个表:
Text | label
=======================
text1 | green txt,red,blue
text2 | black,red,blue
text3 | green txt,blue,black
text4 | black,red,green
我想删除以字符串“txt”结尾的标签,所以我想得到的结果是:
Text | label
=======================
text1 | red,blue
text2 | black,red,blue
text3 | blue,black
text4 | black,red,green
对不起,我编辑了这个问题。
解决方案
您要删除的值都是字符串。如果您的列表还包含其他不以“txt”结尾的字符串,请使用以下命令:
df['label'] = df['label'].apply(lambda values: [val for val in values if not isinstance(val, str) or not val.endswith('txt')])
如果列表中唯一可以出现的字符串是以 'txt' 结尾的字符串,并且您要保留的所有其他值不是字符串而是整数,则更简单:
df['label'] = df['label'].apply(lambda values: [val for val in values if not isinstance(val, str)])
编辑:
回答已编辑的问题:
df['label'] = df['label'].apply(lambda string: ','.join([word for word in string.split(',') if not word.rstrip(' ').endswith('txt')]))
推荐阅读
- python - 查询时的 SQLAlchemy 侦听器
- html - 在 html-5 bsed 主题中从左到右移动侧边栏
- tensorflow - Tensorflow compute_output_shape()不适用于自定义层
- java - 阅读 Dockerfile 命令时遇到问题:是否可以 cd 到 jar 文件中?tar -cf 有什么作用?
- javascript - 电子:通知不是构造函数
- go - 如何从对象中删除属性
- java - BigInteger 常量行为
- c# - 我用来创建表的这条 SQL 语句的语法有什么问题?
- html - 如何设置 Web.config:MVC
- snmp - 设置请求不工作 SNMP4j