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 categoric