【问题标题】:Pandas replace string values in a column which has multiple variationsPandas 替换具有多个变体的列中的字符串值
【发布时间】:2022-06-27 02:57:50
【问题描述】:

我正在处理这个csv file. 这是一个笔记本电脑信息的小型数据集。

laptops = pd.read_csv('laptops.csv',encoding="Latin-1")
laptops["Operating System"].value_counts()

Windows      1125
No OS          66
Linux          62
Chrome OS      27
macOS          13
Mac OS          8
Android         2
Name: Operating System, dtype: int64

我想将 macOS 和 Mac OS 的变体合并到一个值“macOS”下。

我试过了,效果很好。

mapping_dict = {
    'Android': 'Android',
    'Chrome OS': 'Chrome OS',
    'Linux': 'Linux',
    'Mac OS': 'macOS',
    'No OS': 'No OS',
    'Windows': 'Windows',
    'macOS': 'macOS'
}

laptops["Operating System"] = laptops["Operating System"].map(mapping_dict)

laptops["Operating System"].value_counts()

Windows      1125
No OS          66
Linux          62
Chrome OS      27
macOS          21
Android         2
Name: Operating System, dtype: int64

这是唯一的方法还是最好的方法?假设这样的要求可能会出现在多个值上(而不仅仅是 macOS)。

【问题讨论】:

  • 我认为 map 在你的情况下已经足够好了。如果有多个值,您唯一需要更改的只是字典,而不是 map 函数。
  • @RavindraS 查看我的解决方案。我认为它会为您提供您可能正在寻找的灵活性。

标签: python pandas dataframe numpy data-cleaning


【解决方案1】:
laptops['Operating System'] = laptops['Operating System'].str.replace(r'(?i)(mac|mc).*os', 'macOS', regex=True)

【讨论】:

  • 如前所述,这只是解决了 Mac Os 的这种特殊情况。如果还有更多这样的案例怎么办?希望改进我发布的解决方案。
  • @RavindraS:已更新。现在更通用了。这是你想要的?您能否更具体地列出您想用“macOS”替换的确切名称的更多变体?
【解决方案2】:

你可以这样做

laptops['Operating System'] = laptops['Operating System'].replace('Mac OS', 'macOS')

【讨论】:

  • 这只是解决了用“macOS”替换“Mac OS”的一种特殊情况。 mac os 也可以有其他变体。 MAC 操作系统,MC 操作系统。正如我所说,其他值的变化也可能存在。寻找通用解决方案并尝试改进我发布的解决方案。
  • 您可以将其作为列表传递,例如.replace(['Mac OS', 'mac OS'], 'macOS')
  • 您是否掌握了所有变体,或者您正在抱怨它们的数量巨大?
【解决方案3】:

我会这样做:

# Generate a dict of list, where each key is the name you want
# to assign and the lists contain the variations of the main name
aliases = {
    "macOS": ["mac", "osx", "Mac OS"],
    "Windows": ["win", "windows", "Windows"],
}

# Create a map so it's easier to lookup all the names
aliases_map = {v: k for k, v in aliases.items() for v in v}

# Replace all of the aliases with its respective main name
laptops["Operating System"] = laptops["Operating System"].replace(aliases_map)

laptops["Operating System"].value_counts()的输出:

Windows      1125
No OS          66
Linux          62
Chrome OS      27
macOS          21
Android         2
Name: Operating System, dtype: int64

【讨论】:

    【解决方案4】:

    这段代码可以解决问题。但是您必须提前知道可能的变体。万一提前知道不可行,那就是python和pandas标签下不在这里讨论的另一个问题了。

    df['Operating System'][df['Operating System'].str.lower().isin(['mac', 'osx', 'macos'])] = 'Mac OS'

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 2020-01-27
      • 1970-01-01
      • 2018-08-30
      • 2021-03-28
      • 2021-07-02
      • 1970-01-01
      • 2018-04-08
      • 2020-01-09
      相关资源
      最近更新 更多