首页 > 解决方案 > 如何从列中删除不需要的字符串?

问题描述

我的列 df["reviews"] 中有评论,但只有一些评论以字符串“此信息有用吗?....”
结尾,所以如果我的行包含此字符串,我想删除最后的 42字符 [:-42] 其中包括 此信息是否有帮助?

我怎么能在 Pandas 中做到这一点
试过这个但它不起作用

def remove_unwanted(a):
    if "Was this information helpful" in a:
        print(a[:-42])   
    else:
        print("False")
        
# column without yes and no in complaint body
df['cleaned_reviews'] = df.apply(lambda row: remove_unwanted(row['reviews']), axis = 1)

标签: pythonpandasseries

解决方案


试试这个,我想这就是你要找的

df['cleaned_reviews'] = df['reviews'].str.rstrip('Was this information helpful?')

推荐阅读