【问题标题】:How to replace similarly written values that make reference to the same (to give them the same value)? [duplicate]如何替换引用相同的类似书面值(赋予它们相同的值)? [复制]
【发布时间】:2020-07-03 05:02:58
【问题描述】:

我在 pandas DataFrame 中有一个 Cities 列,其中有很多类似但不完全相同的单词。

例如:"Example City"" Example City""Example City "

这让我很困扰,因为当我在列中查找唯一值时,它会将这些城市分类为不同的。

【问题讨论】:

  • 所以唯一的区别是尾随空格?
  • 它有助于与预期输出共享样本数据
  • 请清晰完整地描述您尝试执行的操作。
  • 这能回答你的问题吗? Pandas - Strip white space

标签: python pandas numpy


【解决方案1】:

如果问题只是字符串末尾的空格,您可以使用strip,如果您还有多个空格(例如Example CityExample City),您可以使用replace 和正则表达式:

df['Cities'] = df['Cities'].str.strip()
df['Cities'] = df['Cities'].str.replace(r'\s\s+', ' ')

【讨论】:

  • 它适用于空间,这是问题的主要根源。谢谢。
  • @AMC strip() 删除左侧和右侧的空格,而 lstrip()rstrip() 只做一侧。
猜你喜欢
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 2021-07-20
相关资源
最近更新 更多