【发布时间】: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() 和你的答案,它解决了????