【利用Python进行数据分析】12 - pandas高级应用

1、分类数据

pandas分类数据,如何提高性能和内存的使用率。以及在统计和机器学习中使用分类数据的工具。

1.1、pandas处理重复值常见函数

  • pd.unique(values)
  • pd.value_counts(values) 可以从数组提取出不同的值,并分别计算频率
In [10]: import numpy as np; import pandas as pd

In [11]: values = pd.Series(['apple', 'orange', 'apple',
   ....:                     'apple'] * 2)

In [12]: values
Out[12]: 
0     apple
1    orange
2     apple
3     apple
4     apple
5    orange
6     apple
7     apple
dtype: object

In [13]: pd.unique(values)
Out[13]: array(['apple', 'orange'], dtype=object)

In [14]: pd.value_counts(values)
Out[14]: 
apple     6
orange    2
dtype: int64

1.2、分类编码 series_str.take(values)

许多数据系统(数据仓库、统计计算或其它应用)都发展出了特定的表征重复值的方法,以进行高效的存储和计算。在数据仓库中,最好的方法是使用包含不同值的维表(Dimension Table),将主要的参数存储为引用维表整数键

In [15]: values = pd.Series([0, 1, 0, 0] * 2)

In [16]: dim = pd.Series(['apple', 'orange'])

In [17]: values
Out[17]: 
0    0
1    1
2    0
3    0
4    0
5    1
6    0
7    0
dtype: int64

In [18]: dim
Out[18]: 
0     apple
1    orange
dtype: object
  • 使用take方法存储原始的字符串Series:
    这种用整数表示的方法称为分类或字典编码表示法。不同值得数组称为分类、字典或数据级。表示分类的整数值称为分类编码或简单地称为编码。分类表示可以在进行分析时大大的提高性能。你也可以在保持编码不变的情况下,对分类进行转换。
In [19]: dim.take(values)
Out[19]: 
0     apple
1    orange
0     apple
0     apple
0     apple
1    orange
0     apple
0     apple
dtype: object

分类转换方法例子:

  • 重命名分类。
  • 加入一个新的分类,不改变已经存在的分类的顺序或位置。

1.3、pandas的分类类型

pandas有一个特殊的分类类型df_date.astype(‘category’),用于保存使用整数分类表示法的数据。

  • df[‘fruit’]是一个Python字符串对象的数组,调用它本身,df[‘fruit’].astype(‘category’),转变为分类:
In [20]: fruits = ['apple', 'orange', 'apple', 'apple'] * 2

In [21]: N = len(fruits)

In [22]: 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'])

In [23]: df
Out[23]: 
   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

In [24]: fruit_cat = df['fruit'].astype('category')

In [25]: fruit_cat
Out[25]: 
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]
  • fruit_cat的值不是NumPy数组,而是一个pandas.Categorical实例:
In [26]: c = fruit_cat.values

In [27]: type(c)
Out[27]: pandas.core.categorical.Categorical
  • 分类对象有categories和codes属性:
In [28]: c.categories
Out[28]: Index(['apple', 'orange'], dtype='object')

In [29]: c.codes
Out[29]: array([0, 1, 0, 0, 0, 1, 0, 0], dtype=int8)

可将DataFrame的列通过分配转换结果,转换为分类:

In [30]: df['fruit'] = df['fruit'].astype('category')

In [31]: df.fruit
Out[31]:
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:pd.Categorical([‘foo’, ‘bar’, ‘baz’, ‘foo’, ‘bar’])
In [32]: my_categories = pd.Categorical(['foo', 'bar', 'baz', 'foo', 'bar'])

In [33]: my_categories
Out[33]: 
[foo, bar, baz, foo, bar]
Categories (3, object): [bar, baz, foo]
  • 已经从其它源获得了分类编码,你还可以使用from_codes构造器:d.Categorical.from_codes(codes, categories)
In [34]: categories = ['foo', 'bar', 'baz']

In [35]: codes = [0, 1, 2, 0, 0, 1]

In [36]: my_cats_2 = pd.Categorical.from_codes(codes, categories)

In [37]: my_cats_2
Out[37]: 
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo, bar, baz]
  • 与显示指定不同,分类变换不认定指定的分类顺序。因此取决于输入数据的顺序,categories数组的顺序会不同。当使用from_codes或其它的构造器时,可以指定分类一个有意义的顺序ordered=True:
In [38]: ordered_cat = pd.Categorical.from_codes(codes, categories,
   ....:                                         ordered=True)

In [39]: ordered_cat
Out[39]: 
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo < bar < baz]

  • 输出[foo < bar < baz]指明‘foo’位于‘bar’的前面,以此类推。无序的分类实例可以通过as_ordered排序:
In [40]: my_cats_2.as_ordered()
Out[40]: 
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo < bar < baz]
  • 分类数组可以包括任意不可变类型。

1.4、用分类进行计算 (pd.Series(draws).groupby(bins).agg([‘count’, ‘min’, ‘max’]).reset_index())

与非编码版本(比如字符串数组)相比,使用pandas的Categorical有些类似。某些pandas组件,比如groupby函数,更适合进行分类。还有一些函数可以使用有序标志位。

  • 使用pandas.qcut面元函数,它会返回pandas.Categorical
In [41]: np.random.seed(12345)

In [42]: draws = np.random.randn(1000)

In [43]: draws[:5]
Out[43]: array([-0.2047,  0.4789, -0.5194, -0.5557,  1.9658])

#计算这个数据的分位面元,提取一些统计信息:
In [44]: bins = pd.qcut(draws, 4)

In [45]: bins
Out[45]: 
[(-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.95, -0.684], (-0.0101, 0.63
], (0.63, 3.928]]
Length: 1000
Categories (4, interval[float64]): [(-2.95, -0.684] < (-0.684, -0.0101] < (-0.010
1, 0.63] <
                                    (0.63, 3.928]]
  • 确切的样本分位数与分位的名称相比,不利于生成汇总。可以使用labels参数qcut,实现目的: bins = pd.qcut(draws, 4, labels=[‘Q1’, ‘Q2’, ‘Q3’, ‘Q4’])
In [46]: bins = pd.qcut(draws, 4, labels=['Q1', 'Q2', 'Q3', 'Q4'])

In [47]: bins
Out[47]: 
[Q2, Q3, Q2, Q2, Q4, ..., Q3, Q2, Q1, Q3, Q4]
Length: 1000
Categories (4, object): [Q1 < Q2 < Q3 < Q4]

In [48]: bins.codes[:10]
Out[48]: array([1, 2, 1, 1, 3, 3, 2, 2, 3, 3], dtype=int8)
  • 加上标签的面元分类不包含数据面元边界的信息,可以使用groupby提取一些汇总信息:
In [49]: bins = pd.Series(bins, name='quartile')

In [50]: results = (pd.Series(draws).groupby(bins).agg(['count', 'min', 'max']).reset_index())

In [51]: results
Out[51]: 
  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
  • 分位数列保存了原始的面元分类信息,包括排序:
In [52]: results['quartile']
Out[52]:
0    Q1
1    Q2
2    Q3
3    Q4
Name: quartile, dtype: category
Categories (4, object): [Q1 < Q2 < Q3 < Q4]

1.5、用分类提高性能

如果你是在一个特定数据集上做大量分析,将其转换为分类可以极大地提高效率。DataFrame列的分类使用的内存通常少的多。

#一些包含一千万元素的Series,和一些不同的分类:
In [53]: N = 10000000

In [54]: draws = pd.Series(np.random.randn(N))

In [55]: labels = pd.Series(['foo', 'bar', 'baz', 'qux'] * (N // 4))
#现在,将标签转换为分类:
In [56]: categories = labels.astype('category')
#可以看到标签使用的内存远比分类多:
In [57]: labels.memory_usage()
Out[57]: 80000080

In [58]: categories.memory_usage()
Out[58]: 10000272

  • 转换为分类不是没有代价的,但这是一次性的代价:
In [59]: %time _ = labels.astype('category')
CPU times: user 490 ms, sys: 240 ms, total: 730 ms
Wall time: 726 ms
  • GroupBy使用分类操作明显更快,是因为底层的算法使用整数编码数组,而不是字符串数组。

1.6、分类方法

包含分类数据的Series提供了方便的分类和编码的使用方法,cat属性:

  1. cat属性提供了分类方法的入口:cat_s.cat.codes cat_s.cat.categories
  2. set_categories方法改变实际分类:cat_s.cat.set_categories(actual_categories)
  3. 使用remove_unused_categories方法删除没看到的分类:cat_s3.cat.remove_unused_categories()
In [60]: s = pd.Series(['a', 'b', 'c', 'd'] * 2)

In [61]: cat_s = s.astype('category')

In [62]: cat_s
Out[62]: 
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属性提供了分类方法的入口:
In [63]: cat_s.cat.codes
Out[63]: 
0    0
1    1
2    2
3    3
4    0
5    1
6    2
7    3
dtype: int8
In [64]: cat_s.cat.categories
Out[64]: Index(['a', 'b', 'c', 'd'], dtype='object')
  • 数据的实际分类集,超出了数据中的四个值。可以使用set_categories方法改变它们:
In [65]: actual_categories = ['a', 'b', 'c', 'd', 'e']

In [66]: cat_s2 = cat_s.cat.set_categories(actual_categories)

In [67]: cat_s2
Out[67]: 
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]
  • 增加了新的分类类别,新的分类类别会出现在类别索引中,计数可以为0。使用value_counts查看分类结果。
In [68]: cat_s.value_counts()
Out[68]: 
d    2
c    2
b    2
a    2
dtype: int64

In [69]: cat_s2.value_counts()
Out[69]: 
d    2
c    2
b    2
a    2
e    0
dtype: int64

在大数据集中,分类经常作为节省内存和高性能的便捷工具。

  • 过滤完大DataFrame或Series之后,许多分类可能不会出现在数据中。可以使用remove_unused_categories方法删除没看到的分类:
In [70]: cat_s3 = cat_s[cat_s.isin(['a', 'b'])]

In [71]: cat_s3
Out[71]: 
0    a
1    b
4    a
5    b
dtype: category
Categories (4, object): [a, b, c, d]

In [72]: cat_s3.cat.remove_unused_categories()
Out[72]: 
0    a
1    b
4    a
5    b
dtype: category
Categories (2, object): [a, b]
  • 表12-1列出了可用的分类方法。
    表12-1 pandas的Series的分类方法
    在这里插入图片描述

1.7、为建模创建虚拟变量 pd.get_dummies(cat_s)

  • **使用统计或机器学习工具时,通常会将分类数据转换为虚拟变量,也称为one-hot编码。**这包括创建一个不同类别的列的DataFrame;这些列包含给定分类的1s,其它为0。
In [73]: cat_s = pd.Series(['a', 'b', 'c', 'd'] * 2, dtype='category')
  • pandas.get_dummies函数可以转换这个分类数据为包含虚拟变量的DataFrame:pd.get_dummies(cat_s)
In [74]: pd.get_dummies(cat_s)
Out[74]: 
   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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值