python - 处理 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 名列表中的工作室替换为“其他”
所以问题是,如果有人知道熊猫对此有任何优雅的解决方案吗?这是非常常见的数据清理任务
解决方案
您可以使用pd.DataFrame.loc
布尔索引:
df.loc[~df['studio'].isin(top_8_list), 'studio'] = 'Other'
请注意,无需通过手动for
循环构建您的前 8 个工作室列表:
top_8_list = df['studio'].value_counts().index[:8]
推荐阅读
- android - enoent 文件打开失败&解决方法 InputStream
- java - 用 2 个锚点 ARCore 之间的方向渲染箭头
- javascript - 如何在不同的 HTML 脚本类中引用 javascript 类?
- opengl - 了解图像抖动以及它们如何帮助混合 CSM
- javascript - 如何将函数返回值传递给 Node.js 中的对象
- sql-server - VBA:使用连接表时,sql查询中的对象已关闭错误
- c# - 如何删除从 Web 应用程序发送的电子邮件的 base64 编码
- java - SonarQube + Maven + JaCoCo + GitLab CI:Sonar 在升级到 SonarQube 7.9.2 后开始显示 0% 的代码覆盖率
- javascript - Redux/React 的重构
- javascript - 如何将原始基本 URL 替换为我的自定义 URL?