从熊猫中的字符串中删除子字符串

时间:2020-07-22 14:35:20

标签: python pandas

我正在尝试从下面的数据框中删除所有单词not

d = {'keep': ["not useful", "useful", "not useful", "useful", "useful"]}
df = pd.DataFrame(data=d)
df['keep'] = df['keep'].replace('not', '', inplace=True)
df

这导致我的“保持”列等于None。 不知道我在这里做错了什么。

谢谢

2 个答案:

答案 0 :(得分:2)

两个问题:

  1. inplace=True执行 inplace 操作,因此它直接修改序列并返回None
  2. df['keep'].replace(a,b)替换整个字符串,而不是子字符串。

您要

df['keep'] = df['keep'].replace('not','', regex=True)

答案 1 :(得分:0)

使用:

for i in range(len(df['keep'])):
    df['keep'][i] = df['keep'][i].replace('not', '')