【问题标题】:How to remove unwanted string from column?如何从列中删除不需要的字符串?
【发布时间】:2021-06-24 06:56:31
【问题描述】:

我的一个专栏 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)

【问题讨论】:

  • 您的函数需要 return 而不是 print() 才能使其对数据框产生影响
  • @oskros 将其更改为返回 a[:-42] 它说 TypeError: 'float' 类型的参数不可迭代,我的结尾字符串也包含一些数字,可能是因为那个吗?
  • df['cleaned_reviews'] 中的值似乎并不总是字符串,但有时是浮点数,这就是您收到该错误的原因。你可以写str(a)[:-42]来解决它
  • 哦,是的,它现在确实有效,而且我意识到它也可能是由于 null 值而发生的,所以我也应用了 notnull() 和你的答案,它解决了????

标签: python pandas series


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-01
    • 2011-12-24
    • 2011-08-13
    • 2015-07-06
    • 2015-08-06
    • 2012-11-20
    相关资源
    最近更新 更多