首页 > 解决方案 > 处理 Pandas 中的稀疏类别 - 将不在顶级类别中的所有内容替换为“其他”

问题描述

在清理数据时,我经常会遇到以下常见问题,其中有一些更常见的类别(比如前 10 种电影类型)和很多其他稀疏的类别。例如,这里通常的做法是将稀疏流派组合成“其他”。

当稀疏类别不多时很容易做到:

# Join bungalows as they are sparse classes into 1
df.property_type.replace(['Terraced bungalow','Detached bungalow', 'Semi-detached bungalow'], 'Bungalow', inplace=True)

但是,例如,如果我有一个电影数据集,其中大部分电影由 8 家大工作室制作,并且我想将其他所有内容合并到“其他”工作室下,那么获得前 8 家工作室是有意义的:

top_8_list = []
top_8 = df.studio.value_counts().head(8)
for key, value in top_8.iteritems():
    top_8_list.append(key)

top_8_list
top_8_list
['Universal Pictures',
 'Warner Bros.',
 'Paramount Pictures',
 'Twentieth Century Fox Film Corporation',
 'New Line Cinema',
 'Columbia Pictures Corporation',
 'Touchstone Pictures',
 'Columbia Pictures']

然后做类似的事情

将工作室不在前 8 名列表中的工作室替换为“其他”

所以问题是,如果有人知道熊猫对此有任何优雅的解决方案吗?这是非常常见的数据清理任务

标签: pythonpandasdataframecounterdata-cleaning

解决方案


您可以使用pd.DataFrame.loc布尔索引:

df.loc[~df['studio'].isin(top_8_list), 'studio'] = 'Other'

请注意,无需通过手动for循环构建您的前 8 个工作室列表:

top_8_list = df['studio'].value_counts().index[:8]

推荐阅读