python-处理熊猫中的稀疏类别-用“其他”替换不在顶级类别中的所有内容
作者:互联网
清理数据时,我经常遇到以下常见问题
还有一些更常见的类别(比如说十大电影流派),还有很多其他稀疏的类别.例如,此处通常的做法是将稀疏类型组合为“其他”.
稀疏类别不多时轻松完成:
# 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名中的工作室替换为“其他”
那么问题是,是否有人知道在熊猫中有什么优雅的解决方案?这是非常常见的数据清理任务
解决方法:
您可以将列转换为Categorical
类型,这增加了内存的好处:
top_cats = df.studio.value_counts().head(8).index.tolist() + ['other']
df['studio'] = pd.Categorical(df['studio'], categories=top_cats).fillna('other')
标签:data-cleaning,pandas,dataframe,counter,python 来源: https://codeday.me/bug/20191108/2008475.html