Python学习笔记:类别设置之category与set_categories
作者:互联网
1.设置类别 astype('category')
使用 pandas
可以设置和改变数据的类别。
import pandas as pd
import numpy as np
df = pd.DataFrame({'id':[1,2,3,4,5,6],
'grade':['a','b','b','a','a','e']})
df.info()
df.dtypes
'''
grade object
id int64
dtype: object
'''
将列设置为 category
类型。
df['grade'] = df['grade'].astype('category')
'''
grade category
id int64
dtype: object
Name: grade, dtype: category
Categories (3, object): [a, b, e]
'''
2.改变类别 cat.categories
此时标签集合为3个取值,可通过改变类别标签。
df['grade'].cat.categories = ['very good', 'good', 'bad']
print(df.grade)
'''
0 very good
1 good
2 good
3 very good
4 very good
5 bad
Name: grade, dtype: category
Categories (3, object): [very good, good, bad]
'''
3.改变类别集合 set_categories
改变类别标签集合,原始数据标签不变。
df['grade'] = df['grade'].cat.set_categories(['very bad', 'bad', 'medium', 'good', 'very good'])
df['grade'].cat.set_categories(['very bad', 'bad', 'medium', 'good', 'very good'], inplace=True)
4.按类别排序
按照类别标签在集合中的顺序排序,而不是按照字母顺序排序。
df.sort_values(by='grade')
5.按类别分组
根据类别标签进行分组。
df.groupby('grade').size()
'''
grade
very bad 0
bad 1
medium 0
good 2
very good 3
dtype: int64
'''
标签:category,good,Python,grade,df,bad,set,very,categories 来源: https://www.cnblogs.com/hider/p/15583201.html