针对上述问题,Pandas 提供了分类对象(Categorical Object),该对象能够实现有序排列、自动去重的功能,但是它不能执行运算。本节,我们了解一下分类对象的使用。
import pandas as pd s = pd.Series(["a","b","c","a"], dtype="category") print(s)输出结果:
0 a 1 b 2 c 3 a dtype: category Categories (3, object): [a, b, c]通过上述示例,您可能会注意到,虽然传递给 Series 四个元素值,但是它的类别为 3,这是因为 a 的类别存在重复。
pandas.Categorical(values, categories, ordered)
values:以列表的形式传参,表示要分类的值。import pandas as pd #自动按a、b、c分类 cat = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c']) print(cat)输出结果:
[a, b, c, a, b, c] Categories (3, object): [a, b, c]再看一组示例:
import pandas as pd cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a']) print(cat)输出结果:
[a, b, c, a, b, c, NaN] Categories (3, object): [c, b, a]上述示例中,第二个参数值表示类别,当列表中不存在某一类别时,会自动将类别值设置为 NA。
ordered=True
来实现有序分类。示例如下:
import pandas as pd cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'],ordered=True) print(cat) #求最小值 print(cat.min())输出结果:
[a, b, c, a, b, c, NaN] Categories (3, object): [c < b < a] c
import pandas as pd import numpy as np cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"]) df = pd.DataFrame({"cat":cat, "s":["a", "c", "c", np.nan]}) print(df.describe()) print(df["cat"].describe())输出结果:
cat s count 3 3 unique 2 2 top c c freq 2 2 count 3 unique 2 top c freq 2 Name: cat, dtype: object
obj.categories
命令可以获取对象的类别信息。示例如下:
import pandas as pd import numpy as np s = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"]) print (s.categories)输出结果:
Index(['b', 'a', 'c'], dtype='object')
通过 obj.order 可以获取 order 指定的布尔值:import pandas as pd import numpy as np cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"]) #False表示未指定排序 print (cat.ordered)输出结果:
False
import pandas as pd s = pd.Series(["a","b","c","a"], dtype="category") #对类名重命名 s.cat.categories = ["Group %s" % g for g in s.cat.categories] print(s.cat.categories)输出结果:
Index(['Group a', 'Group b', 'Group c'], dtype='object')
import pandas as pd s = pd.Series(["a","b","c","a"], dtype="category") #追加新类别 s = s.cat.add_categories([5]) #查看现有类别 print(s.cat.categories)输出结果:
Index(['a', 'b', 'c', 5], dtype='object')
import pandas as pd s = pd.Series(["a","b","c","a"], dtype="category") #原序列 print(s) #删除后序列 print(s.cat.remove_categories("a"))输出结果
0 a 1 b 2 c 3 a dtype: category Categories (3, object): [a, b, c] 0 NaN 1 b 2 c 3 NaN dtype: category Categories (2, object): [b, c]
import pandas as pd s1=['a','a','b','d','c'] #当满足两个类别长度相同时 ss0=pd.Categorical(s1,categories=['a','d','b','c']) ss1 = pd.Categorical(s1) print(ss0==ss1)输出结果:
array([ True, True, True, True, True])示例如下:
s1=['a','a','b','d','c'] s2=['a','b','b','d','c'] #满足上述第二个条件,类别相同,并且ordered均为True ss0=pd.Categorical(s1,categories=['a','d','b','c'],ordered=True) ss1 = pd.Categorical(s2,categories=['a','d','b','c'],ordered=True) print(ss0<ss1)输出结果:
array([False, True, False, False, False])
本文链接:http://task.lmcjl.com/news/17309.html