category是一种pandas的类型
pd.Series(["a", "b", "c", "a"], dtype="category")
pd.Series(["a", "b", "c", "a"], dtype="str")
之前自己的代码都是用str,或者直接就是python自己的object类型,那么我们什么时候需要用category而不是str呢?
当 这一列 的值的种类(number of unique)非常少的时候,当需要给这一列的值表示某一个顺序的时候,用category。
- 在做groupby操作的时候可以提速
- 可以节省内存
- 支持order
为什么可以节省内存和提速groupby呢?
猜测是 如果你表明了category,它存储的其实是index,而不是每个值,进行groupby的时候不需要先进行sort操作,所以可以提速和节省内存,这也是它建议你的值的种类比较少的时候用。
官方文档:
This is an introduction to pandas categorical data type, including a short comparison with R’s factor.
Categoricals are a pandas data type corresponding to categorical variables in statistics. A categorical variable takes on a limited, and usually fixed, number of possible values (categories; levels in R). Examples are gender, soc

当数据列的唯一值较少且需要排序时,使用pandas的Category类型而非Str可以提升groupby操作速度并节省内存。Category类型通过存储index优化内存使用,并支持有序操作。了解更多详情,请参阅官方文档。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



