python_分类_category方法

from_codes构造器

Advanced pandas
import numpy as np
import pandas as pd
np.random.seed(12345)
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.set_printoptions(precision=4, suppress=True)
Categorical Data
Background and Motivation
# 背景和⽬的
# 表中的⼀列通常会有重复的包含不同值的⼩集合的情况。我们已
# 经学过了unique和value_counts,它们可以从数组提取出不同的
# 值,并分别计算频率:
import numpy as np; import pandas as pd
values = pd.Series(['apple', 'orange', 'apple',
'apple'] * 2)
values
# pd.unique(values)
# pd.value_counts(values)
0 apple
1 orange
2 apple
3 apple
4 apple
5 orange
6 apple
7 apple
dtype: object
# 以使⽤take⽅法存储原始的字符串Series: 使用take加载series数据
values = pd.Series([0, 1, 0, 0] * 2)
dim = pd.Series(['apple', 'orange'])
values
dim
0 apple
1 orange
dtype: object

# 使用take分类 分桶 为分类或字典编码表示法
# 这种⽤整数表示的⽅法称为分类或字典编码表示法。不同值得数
# 组称为分类、字典或数据级。本书中,我们使⽤分类的说法。表
# 示分类的整数值称为分类编码或简单地称为编码。
# 分类表示可以在进⾏分析时⼤⼤的提⾼性能。你也可以在保持编
# 码不变的情况下,对分类进⾏转换。⼀些相对简单的转变例⼦包
# 括:
# 重命名分类。
# 加⼊⼀个新的分类,不改变已经存在的分类的顺序或位置。
dim.take(values)
0 apple
1 orange
0 apple
0 apple
0 apple
1 orange
0 apple
0 apple
dtype: object
Categorical Type in pandas
pandas的分类类型
# pandas有⼀个特殊的分类类型,⽤于保存使⽤整数分类表示法
# 的数据。看⼀个之前的Series例⼦:
# pandas的分类类型
# pandas有⼀个特殊的分类类型,⽤于保存使⽤整数分类表示法
# 的数据。看⼀个之前的Series例⼦:
fruits = ['apple', 'orange', 'apple', 'apple'] * 2
N = len(fruits)
df = pd.DataFrame({'fruit': fruits,
'basket_id': np.arange(N),
'count': np.random.randint(3, 15, size=N),
'weight': np.random.uniform(0, 4, size=N)},
columns=['basket_id', 'fruit', 'count', 'weight'])
df
basket_id fruit count weight
0 0 apple 5 3.858058
1 1 orange 8 2.612708
2 2 apple 4 2.995627
3 3 apple 7 2.614279
4 4 apple 12 2.990859
5 5 orange 8 3.845227
6 6 apple 5 0.033553
7 7 apple 4 0.425778
fruit_cat的值不是NumPy数组,⽽是⼀个pandas.Categorical实
# 例:
fruit_cat = df['fruit'].astype('category')
fruit_cat
# fruit_cat的值不是NumPy数组,⽽是⼀个pandas.Categorical实
# 例:
0 apple
1 orange
2 apple
3 apple
4 apple
5 orange
6 apple
7 apple
Name: fruit, dtype: category
Categories (2, object): [apple, orange]
c = fruit_cat.values
type(c)
pandas.core.arrays.categorical.Categorical
# 分类对象有categories和codes属性:
c.categories
c.codes

array([0, 1, 0, 0, 0, 1, 0, 0], dtype=int8)
你可将DataFrame的列通过分配转换结果,转换为分类:
# 你可将DataFrame的列通过分配转换结果,转换为分类:
df['fruit'] = df['fruit'].astype('category')
df.fruit
0 apple
1 orange
2 apple
3 apple
4 apple
5 orange
6 apple
7 apple
Name: fruit, dtype: category
Categories (2, object): [apple, orange]
# 还可以从其它Python序列直接创建pandas.Categorical:
my_categories = pd.Categorical(['foo', 'bar', 'baz', 'foo', 'bar'])
my_categories
[foo, bar, baz, foo, bar]
Categories (3, object): [bar, baz, foo]
# 如果你已经从其它源获得了分类编码,你还可以使⽤from_codes
# 构造器:
categories = ['foo', 'bar', 'baz']
codes = [0, 1, 2, 0, 0, 1]
my_cats_2 = pd.Categorical.from_codes(codes, categories)
my_cats_2
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo, bar, baz]
Categorical
# 与显示指定不同,分类变换不认定指定的分类顺序。因此取决于
# 输⼊数据的顺序, categories数组的顺序会不同。当使⽤
# from_codes或其它的构造器时,你可以指定分类⼀个有意义的顺
# 序:
ordered_cat = pd.Categorical.from_codes(codes, categories,
ordered=True)
ordered_cat
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo < bar < baz]
输出[foo < bar < baz]指明‘foo’位于‘bar’的前⾯,以此类推。⽆序
# 的分类实例可以通过as_ordered排序:
# 输出[foo < bar < baz]指明‘foo’位于‘bar’的前⾯,以此类推。⽆序
# 的分类实例可以通过as_ordered排序:
my_cats_2.as_ordered()
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo < bar < baz]
Computations with Categoricals¶
# ⽤分类进⾏计算
# 与⾮编码版本(⽐如字符串数组)相⽐,使⽤pandas的
# Categorical有些类似。某些pandas组件,⽐如groupby函数,更
# 适合进⾏分类。还有⼀些函数可以使⽤有序标志位。
# 来看⼀些随机的数值数据,使⽤pandas.qcut⾯元函数。它会返
# 回pandas.Categorical,我们之前使⽤过pandas.cut,但没解释
# 分类是如何⼯作的:
np.random.seed(12345)
draws = np.random.randn(1000)
draws[:5]
# draws
array([-0.2047, 0.4789, -0.5194, -0.5557, 1.9658])
# 计算这个数据的分位⾯元,提取⼀些统计信息:
bins = pd.qcut(draws, 4)
bins
[(-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: 1000
Categories (4, interval[float64]): [(-2.9499999999999997, -0.684] < (-0.684, -0.0101] < (-0.0101, 0.63] < (0.63, 3.928]]
# 虽然有⽤,确切的样本分位数与分位的名称相⽐,不利于⽣成汇
# 总。我们可以使⽤labels参数qcut,实现⽬的
bins = pd.qcut(draws, 4, labels=['Q1', 'Q2', 'Q3', 'Q4'])
bins
bins.codes[:10]
array([1, 2, 1, 1, 3, 3, 2, 2, 3, 3], dtype=int8)
加上标签的⾯元分类不包含数据⾯元边界的信息,因此可以使⽤
# groupby提取⼀些汇总信息:
# 加上标签的⾯元分类不包含数据⾯元边界的信息,因此可以使⽤
# groupby提取⼀些汇总信息:
bins = pd.Series(bins, name='quartile')
results = (pd.Series(draws)
.groupby(bins)
.agg(['count', 'min', 'max'])
.reset_index())
results
quartile 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
分位数列保存了原始的⾯元分类信息,包括排序:
# 分位数列保存了原始的⾯元分类信息,包括排序:
results['quartile']
0 Q1
1 Q2
2 Q3
3 Q4
Name: quartile, dtype: category
Categories (4, object): [Q1 < Q2 < Q3 < Q4]
#### Better performance with categoricals
labels
# ⽤分类提⾼性能
# 如果你是在⼀个特定数据集上做⼤量分析,将其转换为分类可以
# 极⼤地提⾼效率。 DataFrame列的分类使⽤的内存通常少的多。
# 来看⼀些包含⼀千万元素的Series,和⼀些不同的分类:
N = 10000000
draws = pd.Series(np.random.randn(N))
labels = pd.Series(['foo', 'bar', 'baz', 'qux'] * (N // 4))
现在,将标签转换为分类:
# 现在,将标签转换为分类:
categories = labels.astype('category')
# 这时,可以看到标签使⽤的内存远⽐分类多:
labels.memory_usage()
categories.memory_usage()
10000272
GroupBy操作明显⽐分类快,是因为底层的算法使⽤整数编码数
# 487组,⽽不是字符串数组。
# 转换为分类不是没有代价的,但这是⼀次性的代价:
# GroupBy操作明显⽐分类快,是因为底层的算法使⽤整数编码数
# 487组,⽽不是字符串数组。
%time _ = labels.astype('category')
Wall time: 705 ms
Categorical Methods
# 分类⽅法
# 包含分类数据的Series有⼀些特殊的⽅法,类似于Series.str字符
# 串⽅法。它还提供了⽅便的分类和编码的使⽤⽅法。看下⾯的
# Series:
s = pd.Series(['a', 'b', 'c', 'd'] * 2)
cat_s = s.astype('category')
cat_s
0 a
1 b
2 c
3 d
4 a
5 b
6 c
7 d
dtype: category
Categories (4, object): [a, b, c, d]
# 特别的cat属性提供了分类⽅法的⼊⼝:
cat_s.cat.codes
cat_s.cat.categories
Index(['a', 'b', 'c', 'd'], dtype='object')
假设我们知道这个数据的实际分类集,超出了数据中的四个值。
# 我们可以使⽤set_categories⽅法改变它们:
# 假设我们知道这个数据的实际分类集,超出了数据中的四个值。
# 我们可以使⽤set_categories⽅法改变它们:
actual_categories = ['a', 'b', 'c', 'd', 'e']
cat_s2 = cat_s.cat.set_categories(actual_categories)
cat_s2
0 a
1 b
2 c
3 d
4 a
5 b
6 c
7 d
dtype: category
Categories (5, object): [a, b, c, d, e]
虽然数据看起来没变,新的分类将反映在它们的操作中。例如,
# 如果有的话, value_counts表示分类:
# 虽然数据看起来没变,新的分类将反映在它们的操作中。例如,
# 如果有的话, value_counts表示分类:
cat_s.value_counts()
cat_s2.value_counts()
d 2
c 2
b 2
a 2
e 0
dtype: int64
在打数据集中,分类经常作为节省内存和⾼性能的便捷⼯具。过
# 滤完⼤DataFrame或Series之后,许多分类可能不会出现在数据
# 中。我们可以使⽤remove_unused_categories⽅法删除没看到
# 的分类:
# 在打数据集中,分类经常作为节省内存和⾼性能的便捷⼯具。过
# 滤完⼤DataFrame或Series之后,许多分类可能不会出现在数据
# 中。我们可以使⽤remove_unused_categories⽅法删除没看到
# 的分类:
cat_s3 = cat_s[cat_s.isin(['a', 'b'])]
cat_s3
cat_s3.cat.remove_unused_categories()
0 a
1 b
4 a
5 b
dtype: category
Categories (2, object): [a, b]



Creating dummy variables for modeling¶
# 为建模创建虚拟变量
# 当你使⽤统计或机器学习⼯具时,通常会将分类数据转换为虚拟
# 变量,也称为one-hot编码。这包括创建⼀个不同类别的列的
# DataFrame;这些列包含给定分类的1s,其它为0。
# 看前⾯的例⼦:
cat_s = pd.Series(['a', 'b', 'c', 'd'] * 2, dtype='category')
cat_s
0 a
1 b
2 c
3 d
4 a
5 b
6 c
7 d
dtype: category
Categories (4, object): [a, b, c, d]
前⾯的第7章提到过, pandas.get_dummies函数可以转换这个以
# 为分类数据为包含虚拟变量的DataFrame:
# 前⾯的第7章提到过, pandas.get_dummies函数可以转换这个以
# 为分类数据为包含虚拟变量的DataFrame:
pd.get_dummies(cat_s)
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