处理熊猫中的稀疏类别-用“其他”替换不在顶级类别中的所有内容

时间:2018-10-05 10:20:10

标签: python pandas dataframe counter data-cleaning

在清理数据时,我经常遇到以下常见问题 还有一些更常见的类别(比如说十大电影流派),还有很多其他稀疏的类别。例如,此处通常的做法是将稀疏类型结合到“其他”中。

在稀疏类别不多的情况下很容易做到:

# 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名中的工作室

那么问题是,如果有人知道在熊猫中有什么优雅的解决方案吗?这是非常常见的数据清理任务

2 个答案:

答案 0 :(得分:2)

您可以将pd.DataFrame.loc与布尔索引一起使用:

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

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

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

答案 1 :(得分:1)

您可以将列转换为Categorical类型,这增加了内存的好处:

top_cats = df.studio.value_counts().head(8).index.tolist() + ['other']
df['studio'] = pd.Categorical(df['studio'], categories=top_cats).fillna('other')