python pandas:用特殊字符替换另一个str列中该列的str值

时间:2018-12-27 02:47:51

标签: python python-3.x string pandas

有一个如下数据框。

   id     num     text
   1      1.2     price is 1.2
   1      2.3     price is 1.2 or 2.3
   2      3     The total value is $3 and $130
   3      5     The apple value is 5dollar and $150

我想用字符“ UNK”替换文本中的num

,新的数据框更改为:

   id     num     text
   1      1.2     price is UNK
   1      2.3     price is 1.2 or UNK
   2      3    The total value is UNK and 130
   3      5     The apple value is UNK dollar and $150

z 我当前的代码如下

df_dev['text'].str.replace(df_dev['num'], 'UNK')

有错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

2 个答案:

答案 0 :(得分:2)

让我们使用regexreplace

df.text.replace(regex=r'(?i)'+ df.num.astype(str),value="UNK")
0              price is UNK
1       price is 1.2 or UNK
2    The total value is UNK
Name: text, dtype: object

#df.text=df.text.replace(regex=r'(?i)'+ df.num.astype(str),value="UNK")

更新

(df.text+' ').replace(regex=r'(?i) '+ df.num.astype(str)+' ',value=" UNK ")
0                      price is UNK 
1               price is 1.2 or UNK 
2    The total value is UNK and 130 
Name: text, dtype: object

答案 1 :(得分:1)

该错误是正确的,您无法向expects a string or regular expression的方法提供序列。

Pandas字符串方法不是矢量化的,即它们在后台涉及Python级循环,因此列表理解可能会很好地工作:

zipper = zip(df['text'], df['num'].astype(str))
df['text'] = [text.replace(num, 'UNK') for text, num in zipper]