分类的目的是提高性能和内存的使用率
用整数表示的方法称为分类或者字典编码表示法,不同值的数组称为分类、字典或者数据集。
创建分类take方法存储原始字符串Series直接创建分类:pd.Categorical(data)转变成类:df.astype('category')分类对象属性 codescategories分类计算面元函数qcut函数返回类Categories对象:pd.qcut(draws, 4)通过labels标签实现汇总groupby提取汇总信息代码语言:javascript复制import numpy as npimport pandas as pdfrom pandas import Series, DataFrame代码语言:javascript复制results = (pd.Series(draws).groupby(bins).agg(['count', 'min', 'max']).reset_index())分类方法memory_usage():查看内存cat():提供入口 pd.cat.categoriespd.cat.codesvalue_counts():查看具体分类创建虚拟变量,用0/1组成的矩阵代码语言:javascript复制values = pd.Series(['apple', 'orange', 'apple', 'apple'] * 2)pd.unique(values) # 选取唯一值代码语言:javascript复制array(['apple', 'orange'], dtype=object)代码语言:javascript复制pd.value_counts(values)# 计算每个值出现的频率代码语言:javascript复制apple 6orange2dtype: int64数据系统使用包含不同值的维表Dimension Table ,将主要的参数存储为引用维表整数键
take()方法:分类去重显示代码语言:javascript复制values = pd.Series([0, 1, 0, 0] * 2)dim = pd.Series(['apple', 'orange'])代码语言:javascript复制print(values)print(dim)代码语言:javascript复制0011203040516070dtype: int640 apple1orangedtype: object代码语言:javascript复制dim.take(values)# take方法代码语言:javascript复制0 apple1orange0 apple0 apple0 apple1orange0 apple0 appledtype: objectpandas分类类型代码语言:javascript复制fruits = ['apple', 'orange', 'apple', 'apple'] * 2N = len(fruits)代码语言:javascript复制df = pd.DataFrame({'fruit': fruits,'basket_id': np.arange(N),'count': np.random.randint(3, 15, size=N),# 生成3-15随机整数'weight': np.random.uniform(0, 4, size=N)}, # 生成0-4的数columns=['basket_id', 'fruit', 'count', 'weight'])df.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
basket_id
fruit
count
weight
0
0
apple
12
1.550912
1
1
orange
6
3.457292
2
2
apple
3
3.986303
3
3
apple
7
0.955448
4
4
apple
9
1.912784
5
5
orange
6
1.405372
6
6
apple
11
2.882363
7
7
apple
12
2.137783
转成分类通过astype(‘category’)将某个属性转成分类类型
代码语言:javascript复制# 转换成分类fruit_cat = df['fruit'].astype('category')fruit_cat代码语言:javascript复制0 apple1orange2 apple3 apple4 apple5orange6 apple7 appleName: fruit, dtype: categoryCategories (2, object): [apple, orange]代码语言:javascript复制print(type(fruit_cat))# S型数据代码语言:javascript复制c = fruit_cat.valuesttype(c) # c是⼀个pandas.Categorical实例代码语言:javascript复制pandas.core.arrays.categorical.Categorical两个属性值codes 和 categories代码语言:javascript复制# 分类对象有categories和codes属性print(c.categories) # categories是具体的分类print(c.codes)# codes是里面的0、1值代码语言:javascript复制Index(['apple', 'orange'], dtype='object')[0 1 0 0 0 1 0 0]代码语言:javascript复制df.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
basket_id
fruit
count
weight
0
0
apple
12
1.550912
1
1
orange
6
3.457292
2
2
apple
3
3.986303
3
3
apple
7
0.955448
4
4
apple
9
1.912784
5
5
orange
6
1.405372
6
6
apple
11
2.882363
7
7
apple
12
2.137783
代码语言:javascript复制# 将列转换成分类df['fruit'] = df['fruit'].astype("category")df.fruit代码语言:javascript复制0 apple1orange2 apple3 apple4 apple5orange6 apple7 appleName: fruit, dtype: categoryCategories (2, object): [apple, orange]代码语言:javascript复制# 通过Python其他序列创建分类my_categories = pd.Categorical(['foo', 'bar', 'baz', 'foo', 'bar'])my_categories代码语言:javascript复制[foo, bar, baz, foo, bar]Categories (3, object): [bar, baz, foo]代码语言:javascript复制# 通过from_codes构建分类categories = ['foo', 'bar', 'baz']codes = [0, 1, 2, 0, 0, 1]my_cats_2 = pd.Categorical.from_codes(codes, categories) # from_codes构造器my_cats_2代码语言:javascript复制[foo, bar, baz, foo, foo, bar]Categories (3, object): [foo, bar, baz]代码语言:javascript复制# 无序的分类实例通过as_ordered进行排序my_cats_2.as_ordered()代码语言:javascript复制[foo, bar, baz, foo, foo, bar]Categories (3, object): [foo < bar < baz]代码语言:javascript复制# 创建分类的实例直接指定顺序: ordered=Trueordered_cat = pd.Categorical.from_codes(codes, categories,ordered=True)ordered_cat代码语言:javascript复制[foo, bar, baz, foo, foo, bar]Categories (3, object): [foo < bar < baz]分类计算重点关注pandas中的Categorical类。通过使用pandas.qcut面元函数,返回pandas.Categorical
创建面元通过面元提取数据代码语言:javascript复制np.random.seed(12345)draws = np.random.randn(1000)draws[:5]代码语言:javascript复制array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057])代码语言:javascript复制bins = pd.qcut(draws, 4)bins代码语言:javascript复制[(-0.684, -0.0101], (-0.0101, 0.63], (-0.684, -0.0101], (-0.684, -0.0101], (0.63, 3.928], ..., (-0.0101, 0.63], (-0.684, -0.0101], (-2.9499999999999997, -0.684], (-0.0101, 0.63], (0.63, 3.928]]Length: 1000Categories (4, interval[float64]): [(-2.9499999999999997, -0.684] < (-0.684, -0.0101] < (-0.0101, 0.63] < (0.63, 3.928]]使用lables参数来qcut代码语言:javascript复制bins = pd.qcut(draws, 4, labels=['Q1', 'Q2', 'Q3', 'Q4'])bins代码语言:javascript复制[Q2, Q3, Q2, Q2, Q4, ..., Q3, Q2, Q1, Q3, Q4]Length: 1000Categories (4, object): [Q1 < Q2 < Q3 < Q4]代码语言:javascript复制bins.codes[:10]代码语言:javascript复制array([1, 2, 1, 1, 3, 3, 2, 2, 3, 3], dtype=int8)代码语言:javascript复制# groupby 提取汇总信息bins = pd.Series(bins, name="quratile")results = (pd.Series(draws) .groupby(bins) .agg(["count", "min", "max"]) .reset_index())results.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
quratile
count
min
max
0
Q1
250
-2.949343
-0.685484
1
Q2
250
-0.683066
-0.010115
2
Q3
250
-0.010032
0.628894
3
Q4
250
0.634238
3.927528
代码语言:javascript复制bins = pd.Series(bins, name="quratile")result = (pd.Series(draws) .groupby(bins) .agg(["count", "min", "max"]))result.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
count
min
max
quratile
Q1
250
-2.949343
-0.685484
Q2
250
-0.683066
-0.010115
Q3
250
-0.010032
0.628894
Q4
250
0.634238
3.927528
代码语言:javascript复制results["quratile"]代码语言:javascript复制0Q11Q22Q33Q4Name: quratile, dtype: categoryCategories (4, object): [Q1 < Q2 < Q3 < Q4]分类提高性能使用DF的列分类占用内存少memory_usage():查看内存代码语言:javascript复制N = 10000000draws = pd.Series(np.random.randn(N))labels = pd.Series(['foo', 'bar', 'baz', 'qux'] * (N // 4))代码语言:javascript复制categories = labels.astype("category")categories.memory_usage() # 分类占用内存少代码语言:javascript复制10000272代码语言:javascript复制labels.memory_usage()# 非分类占用内存多代码语言:javascript复制80000080代码语言:javascript复制%time _ = labels.astype('category')代码语言:javascript复制Wall time: 444 ms分类方法先使用分类入口:cat方法;再使用codes,categories方法 cat.codescat.categoriesset_categories:解决超出给定的数据集个数value_counts():查看分类的个数remove_unused_categories():删除没有看到的数据常用方法汇总方法
作用
add_categories
已存在分类的后面直接添加
as_ordered
使分类有序
as_unordered
使分类无序
remove_categories
移除分类,设置移除值为null
remove_unused_categories
移除任意不出现在数据中的分类值
set_categories
用指定的新分类的名字来替换分类,可以添加或者删除分类
代码语言:javascript复制s = pd.Series(['a', 'b', 'c', 'd'] * 2)cat_s = s.astype('category') # 如何转换成分类cat_s代码语言:javascript复制0a1b2c3d4a5b6c7ddtype: categoryCategories (4, object): [a, b, c, d]代码语言:javascript复制# cat属性提供分类方法的入口cat_s.cat.codes代码语言:javascript复制0011223340516273dtype: int8代码语言:javascript复制cat_s.cat.categories代码语言:javascript复制Index(['a', 'b', 'c', 'd'], dtype='object')代码语言:javascript复制# 实际分类超出给定数据集中的个数,通过set_catgories实现actual_categories = ['a', 'b', 'c', 'd', 'e']cat_s2 = cat_s.cat.set_categories(actual_categories)cat_s2代码语言:javascript复制0a1b2c3d4a5b6c7ddtype: categoryCategories (5, object): [a, b, c, d, e]代码语言:javascript复制# 统计每个类的分类值cat_s.value_counts()代码语言:javascript复制d2c2b2a2dtype: int64代码语言:javascript复制cat_s2.value_counts()代码语言:javascript复制d2c2b2a2e0dtype: int64代码语言:javascript复制# remove_unused_categories()cat_s3 = cat_s[cat_s.isin(['a', 'b'])]cat_s3代码语言:javascript复制0a1b4a5bdtype: categoryCategories (4, object): [a, b, c, d]代码语言:javascript复制cat_s.isin(['a', 'b'])代码语言:javascript复制0 True1 True2False3False4 True5 True6False7Falsedtype: bool代码语言:javascript复制# 查看分类,变成2个cat_s3.cat.remove_unused_categories()代码语言:javascript复制0a1b4a5bdtype: categoryCategories (2, object): [a, b]创建虚拟变量虚拟变量创建的过程实际上是将各个分类的标签看成是列属性,存在的数据则是1,不存在则是0,创建0/1矩阵
分类数据转成虚拟变量:one-hot编码创建值为0或者1的DF数据pd.get_dummies()代码语言:javascript复制cat_s = pd.Series(['a', 'b', 'c', 'd'] * 2, dtype='category')pd.get_dummies(cat_s).dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
a
b
c
d
0
1
0
0
0
1
0
1
0
0
2
0
0
1
0
3
0
0
0
1
4
1
0
0
0
5
0
1
0
0
6
0
0
1
0
7
0
0
0
1
代码语言:javascript复制cat_s代码语言:javascript复制0a1b2c3d4a5b6c7ddtype: categoryCategories (4, object): [a, b, c, d]