【发布时间】: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