Data Whale第20期组队学习 Pandas学习—分类数据
一、cat对象
1.1 cat对象的属性
在 pandas 中提供了 category 类型,使用户能够处理分类类型的变量,将一个普通序列转换成分类变量可以使用 astype 方法。
import pandas as pd
import numpy as np
df= pd.read_csv('D:/binchen/txzq/data/learn_pandas.csv',usecols = ['Grade', 'Name', 'Gender', 'Height', 'Weight'])
Sg=df.Grade.astype('category')
print("Sg.head()=\n",Sg.head())
# Sg.head()=
# 0 Freshman
# 1 Freshman
# 2 Senior
# 3 Sophomore
# 4 Sophomore
# Name: Grade, dtype: category
# Categories (4, object): ['Freshman', 'Junior', 'Senior', 'Sophomore']
"在一个分类类型的 Series 中定义了 cat 对象,定义了一些属性和方法来进行分类类别的操作。"
print("Sg.cat=",Sg.cat)
# Sg.cat= <pandas.core.arrays.categorical.CategoricalAccessor object at 0x0000020B6A6D3B00>
print("Sg.cat.categories=",Sg.cat.categories)
# Sg.cat.categories= Index(['Freshman', 'Junior', 'Senior', 'Sophomore'], dtype='object')
print("Sg.cat.ordered=",Sg.cat.ordered)
# Sg.cat.ordered= False
"每一个序列的类别会被赋予唯一的整数编号,它们的编号取决于 cat.categories 中的顺序,该属性可以通过 codes 访问"
print("Sg.cat.codes.head()=",Sg.cat.codes.head())
# Sg.cat.codes.head()= 0 0
# 1 0
# 2 2
# 3 3
# 4 3
# dtype: int8
1.2 类别的增加、删除和修改
通过 cat 对象的 categories 属性能够完成对类别的查询,应该如何进行“增改查删”的其他三个操作呢?首先,对于类别的增加可以使用 add_categories ;若要删除某一个类别可以使用 remove_categories ,同时所有原来序列中的该类会被设置为缺失;可以使用 set_categories 直接设置序列的新类别,原来的类别中如果存在元素不属于新类别,那么会被设置为缺失。如果想要删除未出现在序列中的类别,可以使用 remove_unused_categories 来实现;最后,“增改查删”中还剩下修改的操作,这可以通过 rename_categories 方法完成,同时需要注意的是,这个方法会对原序列的对应值也进行相应修改。
"可以使用 add_categories 增加类别"
S1=Sg.cat.add_categories('Graduate') # 增加一个毕业生类别
print("S1.cat.categories=",S1.cat.categories)
# S1.cat.categories= Index(['Freshman', 'Junior', 'Senior', 'Sophomore', 'Graduate'], dtype='object')
"删除大一的类别使用 remove_categories"
S2=Sg.cat.remove_categories('Freshman')
print("S2.cat.categories=",S2.cat.categories)
# S2.cat.categories= Index(['Junior', 'Senior', 'Sophomore'], dtype='object')
print("S2.head()=",S2.head())
# S2.head()= 0 NaN
# 1 NaN
# 2 Senior
# 3 Sophomore
# 4 Sophomore
# Name: Grade, dtype: category
# Categories (3, object): ['Junior', 'Senior', 'Sophomore']
"使用 set_categories 直接设置序列的新类别"
S3=Sg.cat.set_categories(['Sophomore','PhD']) # 新类别为大二学生和博士
print("S3.cat.categories=",S3.cat.categories)
# S3.cat.categories= Index(['Sophomore', 'PhD'], dtype='object')
print("S3.head()=",S3.head())
# S3.cat.categories= Index(['Sophomore', 'PhD'], dtype='object')
# S3.head()= 0 NaN
# 1 NaN
# 2 NaN
# 3 Sophomore
# 4 Sophomore
# Name: Grade, dtype: category
# Categories (2, object): ['Sophomore', 'PhD']
"使用 remove_unused_categories 删除未出现在序列中的类别"
S4=S3.cat.remove_unused_categories() # 移除了未出现的博士生类别
print(

本文详细介绍了Pandas中的cat对象,包括其属性操作如类别增删改、有序分类的建立与比较,以及区间类别通过cut和qcut的创建与管理。涵盖了数据分类的各个方面,适合进阶Pandas使用者参考。
最低0.47元/天 解锁文章
1768





