首页 > 解决方案 > 正则表达式替换预期的字符串或类似字节的对象

问题描述

我有以下代码,我通过 Pandas 导入了一个数据集,并试图用逗号替换数字(例如,"12,000"),但我似乎总是遇到错误"TypeError: expected string or bytes-like object"

df = pd.read_csv("C:/Users/Dell/Downloads/osc_samples_without.csv")
df2=df.loc[:,['Id','Description']]
df['Description'] = df['Description'].apply(lambda x:re.sub(r'(?<=\d)[,\.]','', df2))

我是 Python 和 Regex 的新手,因此将不胜感激。

标签: pythonregexpandas

解决方案


您可以replace直接使用而无需re显式使用:

df2['Description'] = df2['Description'].str.replace(r'(?<=\d)[.,]', '')

这里,

  • (?<=\d)- 与紧接在数字前面的位置相匹配的正向后视
  • [.,]- 匹配一个.,

推荐阅读