首页 > 解决方案 > 如何删除以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

对不起,我编辑了这个问题。

标签: pythondataframelabelmultilabel-classification

解决方案


您要删除的值都是字符串。如果您的列表还包含其他不以“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')]))

推荐阅读