You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas Categorical布尔切片后保留未使用分类,如何优雅处理?

解决Pandas分类列切片后保留未使用分类的问题

问题场景

把连续数据转成Categorical类型后,做布尔切片(比如筛选timepoint < 11),数据能被正确筛选,但分类列的categories还留着所有原始分类,导致绘图时X轴会显示没被选中的分类值(比如11及以上),影响可视化效果。现在想找不用来回转换数据类型的优雅处理方式,替代先切片再转分类、转数值再转回分类这类繁琐方法。

测试代码

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

### MAKE TESTDATA
df = sns.load_dataset("fmri")

df["timepoint"] = pd.Categorical(df["timepoint"], ordered=True)

### PERFORM BOOLEAN SLICING
df = df.loc[df["timepoint"] < 11]
# df = df.where(df["timepoint"] < 11)  # SAME RESULT

g = sns.catplot(data=df, y="signal", x="timepoint")

优雅解决方案

直接用Pandas Categorical类型自带的remove_unused_categories()方法,一步移除未使用的分类,不需要来回转换数据类型:

修改后的完整代码

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

### MAKE TESTDATA
df = sns.load_dataset("fmri")

df["timepoint"] = pd.Categorical(df["timepoint"], ordered=True)

### PERFORM BOOLEAN SLICING
df = df.loc[df["timepoint"] < 11]

# 移除未被使用的分类
df["timepoint"] = df["timepoint"].cat.remove_unused_categories()

g = sns.catplot(data=df, y="signal", x="timepoint")

效果说明

执行cat.remove_unused_categories()后,timepoint列的categories会自动更新为切片后实际存在的分类值,此时绘图的X轴只会显示筛选后的分类,不会再出现多余的未选中值。

这个方法直接针对Categorical列的cat属性操作,完全不需要转换数据类型,是最简洁高效的处理方式。

内容的提问来源于stack exchange,提问作者markur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:15:26