我在清理数据时经常遇到以下常见问题
有一些比较常见的类别(比如说前十大电影类型)和很多其他的类别是稀疏的这里通常的做法是将稀疏的体裁组合成“其他”例如。
在稀疏类别不多的情况下很容易做到:

# 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']

然后做一些类似的事情
用“其他”替换studio,其中studio不在前8个列表中
那么问题是,是否有人知道熊猫的优雅解决方案?这是非常常见的数据清理任务

最佳答案

您可以将列转换为Categorical类型,这增加了内存优势:

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

关于python - 处理 Pandas 中的稀疏类别-用“其他”替换不在顶级类别中的所有内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52663432/

10-11 03:08
查看更多