处理 Pandas 中的稀疏类别 - 将所有不在顶级类别中的内容替换为 "Other"
Dealing with sparse categories in Pandas - replace everything not in top categories with "Other"
我在清理数据时经常遇到以下常见问题
还有一些更常见的类别(比如前 10 名电影类型)和许多其他稀疏的类别。例如,这里通常的做法是将稀疏类型组合成 "Other"。
稀疏类别不多时轻松完成:
# Join bungalows as they are sparse classes into 1
df.property_type.replace(['Terraced bungalow','Detached bungalow', 'Semi-detached bungalow'], 'Bungalow', inplace=True)
但是,例如,如果我有一个电影数据集,其中大部分电影是由 8 个大工作室制作的,我想将其他所有内容组合在 "other" 工作室下,那么获得前 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 名的工作室替换为 "other"
所以问题是,是否有人知道 pandas 中对此有任何优雅的解决方案?这是很常见的数据清理任务
您可以将列转换为 Categorical
类型,这增加了内存优势:
top_cats = df.studio.value_counts().head(8).index.tolist() + ['other']
df['studio'] = pd.Categorical(df['studio'], categories=top_cats).fillna('other')
您可以将 pd.DataFrame.loc
与布尔索引一起使用:
df.loc[~df['studio'].isin(top_8_list), 'studio'] = 'Other'
请注意,无需通过手动 for
循环构建前 8 个工作室的列表:
top_8_list = df['studio'].value_counts().index[:8]
我在清理数据时经常遇到以下常见问题 还有一些更常见的类别(比如前 10 名电影类型)和许多其他稀疏的类别。例如,这里通常的做法是将稀疏类型组合成 "Other"。
稀疏类别不多时轻松完成:
# Join bungalows as they are sparse classes into 1
df.property_type.replace(['Terraced bungalow','Detached bungalow', 'Semi-detached bungalow'], 'Bungalow', inplace=True)
但是,例如,如果我有一个电影数据集,其中大部分电影是由 8 个大工作室制作的,我想将其他所有内容组合在 "other" 工作室下,那么获得前 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 名的工作室替换为 "other"
所以问题是,是否有人知道 pandas 中对此有任何优雅的解决方案?这是很常见的数据清理任务
您可以将列转换为 Categorical
类型,这增加了内存优势:
top_cats = df.studio.value_counts().head(8).index.tolist() + ['other']
df['studio'] = pd.Categorical(df['studio'], categories=top_cats).fillna('other')
您可以将 pd.DataFrame.loc
与布尔索引一起使用:
df.loc[~df['studio'].isin(top_8_list), 'studio'] = 'Other'
请注意,无需通过手动 for
循环构建前 8 个工作室的列表:
top_8_list = df['studio'].value_counts().index[:8]