在pandas中,跟整型(int)、字符串(str)等类型类似,类别型数据类型在pandas中也是一种数据类型。
1.构造类别型数据变量
① 用Series的dtype参数:
import pandas as pd
a1 = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
② 用Series的astype()方法, astype()方法是pandas的类型转换方法,参数中传入类型名字,可将数组转换成指定类型。
a1 = pd.Series(['a', 'b', 'c', 'a'])
a2 = a1.astype('category')
③ 用pd.Categorical()构建对象,传入参数order=True,基于该对象构建Series,得到有序型的类别数据。
a1 = pd.Series( pd.Categorical(['差', '中', '良', '优'], ordered=True))
注意:需要按自己定义的顺序来定义类别,在构造Categorical对象的时候,还需要提供一个参数:categories,默认categories中的顺序为从小到大。
a1 = pd.Series( pd.Categorical(['差', '中', '良', '优'], categories=['差', '中', '良', '优'], ordered=True))
2.类别类型数据的基本操作-使用.cat属性
① 使用 .cat.categories查看类别名称列表
a1 = pd.Series(['a', 'b', 'c', 'c'], dtype='category')
s.cat.categories
outcome: Index(['a', 'b', 'c'], dtype='object')
② 使用 .cat.ordered 查看类别是否有序
a1 = pd.Series( pd.Categorical(['差', '中', '良', '优'], categories=['差', '中', '良', '优'], ordered=True))
a1.cat.ordered
outcome: True
a2 = pd.Series(['a', 'b', 'c', 'c'], dtype='category')
a2.cat.ordered
outcome:False
③ 读取/修改类别值:cat.categories
a1 = pd.Series(['a', 'b', 'c', 'c'], dtype='category')
a1.cat.categories
outcome: Index(['a', 'b', 'c'], dtype='object')
a1.cat.categories=['类别a', '类别b', 'c']
a1
outcome: 0 类别a
1 类别b
2 c
3 c
dtype: category
Categories (3, object): [类别a, 类别b, c]
④ 使用 .cat.rename_categories() 修改类别名,需赋值给一个新变量,不会改变调用它的变量上。
⑤ 添加新类别 .cat.add_categories(),新类别以列表形式传入。
a2 = a1.cat.add_categories(['类别7','类别8'])
⑥ 删除类别 .cat.remove_categories(),该方法也不作用于调用它的变量。