Pandas是基于Numpy开发的Python库,其提供了大量高效处理数据的模型和方法,是进行数据处理的有力工具。本文将简单介绍pandas中的Series对象的基本操作。
实例化与索引切片
结构与实例化
Pandas的Series对象是能够保存任何类型的数据(整数,字符串,浮点数,Python对象等)的一维数组。其与一般数组的最大区别在于能够定义灵活的索引。
与大多数类数组的对象相同,创建Series对象最直接的方法是用一个一维数组作为实例化的参数。
import pandas as pd
data = pd.Series([0.25, 0.5, 0.75, 1.0])
print(data)
"""
Out: 0 0.25
1 0.50
2 0.75
3 1.00
dtype: float64
"""
可以看到输出一个Series对象时除了数据以外也会输出它们的索引。事实上,Series对象可以认为是索引与其对应数据的结合。通过Series对象的values属性和index属性可以分别单独获取Series的数据和索引。其数据是类似Numpy中ndarray的数组,索引是类型为pd.Index的类数组对象。
print(data.values)
#Out: array([ 0.25, 0.5 , 0.75, 1. ])
print(data.index)
#Out: RangeIndex(start=0, stop=4, step=1)
Series具有与普通列表相同的取值、切片方法,而且还支持自定义的索引。要在创建Series时定义索引,只需传递index参数。index默认为0…n-1的整数序列,而其类型可以是任意类数组类型。
data = pd.Series([0.25, 0.5, 0.75, 1.0], index=['a', 'b', 'c', 'd'])
"""
Out: a 0.25
b 0.50
c 0.75
d 1.00
dtype: float64
"""
print(data["b"])
#Out: 0.5
如果用字典类型初始化Series,则字典的键会被自动转为Series的索引。
population_dict = {'California': 38332521,'Texas': 26448193, 'New York': 19651127, 'Florida': 19552860, 'Illinois': 12882135}
population = pd.Series(population_dict)
print(population)
"""
Out: California 38332521
Florida 19552860
Illinois 12882135
New York 19651127
Texas 26448193
dtype: int64
"""
对于字符串型的索引,Series会将其按字典序排列。此时切片依然有效:
print(population['California':'Illinois'])
"""
Out: California 38332521
Florida 19552860
Illinois 12882135
dtype: int64
"""
索引与切片
细心的朋友可能已经发现了,与普通列表的切片不同,上面的切片则两端都能够取到,这是因为上面使用的是显式索引,即直接使用index中的元素对数据索引。Series还提供隐式索引,即使index不是0…n-1的整数,依然可以用这些整数来获取相应位置的数据。
print(population[1:3])
"""
Out: California 38332521
Florida 19552860
dtype: int64
"""
并且此时切片的结果与普通列表一样是含头不含尾的。
由于显式和隐式切片规则不同,而且当索引为整数时a[3]
这样的表达式会让人产生歧义,不能看出究竟是使用了显式索引还是隐式索引(实际上会优先使用显式索引),从而使代码可读性下降。为了避免这样的问题,Pandas提供了索引器来作为取值的方法。索引器不是方法,而是暴露切片接口的Series对象的属性。
- loc属性:表示使用显式索引
data = pd.Series(['a', 'b', 'c'], index=[1, 3, 5])
print(data.loc[1])
#Out: 'a'
print(data.loc[1:3])
"""
Out: 1 a
3 b
dtype: object
"""
- iloc属性:表示使用隐式索引
print(data.iloc[1])
#Out: "b"
print(data.iloc[1:3])
"""
Out: 3 b
5 c
dtype: object
"""
虽然默认优先使用显式索引,但通过使用索引器,能够增加代码的可读性,还能减少因错误使用索引产生bug的情况,因此强烈建议养成使用索引器的好习惯。
与Numpy的ndarray类似,Series也支持布尔索引和花式索引。
print(population[(population>10000000)&(population<15000000)]
"""
Out: Illinois 12882135
dtype: int64
"""
print(population[['Florida','Texas']])
"""
Out: Florida 19552860
Texas 26448193
dtype: int64
"""
字符串与正则表达式方法
字符串方法
向量化字符串方法,可以简单理解成是对数据为字符串类型的Series中的数据进行字符串方法的批处理。几乎所有的Python内置的字符串方法都被复制到Pandas的向量化字符串方法中,这意味着使用Series可以完成Python中的绝大多数字符串操作。
示例1:
monte = pd.Series(['Graham Chapman', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones', 'Michael Palin'])
print(monte.str.lower())
"""
Out:
0 graham chapman
1 john cleese
2 terry gilliam
3 eric idle
4 terry jones
5 michael palin
dtype: object
"""
示例2:
print(monte.str.split())
"""
Out:
0 [Graham, Chapman]
1 [John, Cleese]
2 [Terry, Gilliam]
3 [Eric, Idle]
4 [Terry, Jones]
5 [Michael, Palin]
dtype: object
"""
Series还有一些自带的字符串处理方法,如下图
具体效果可以自行尝试
正则表达式方法
Series.str
还能够支持正则表达式方法,如下图
示例1:
print(monte.str.extract('([A-Za-z]+)'))
"""
Out:
0 Graham
1 John
2 Terry
3 Eric
4 Terry
5 Michael
dtype: object
"""
示例2:
print(monte.str.findall(r'^[^AEIOU].*[^aeiou]$'))
"""
Out:
0 [Graham Chapman]
1 []
2 [Terry Gilliam]
3 []
4 [Terry Jones]
5 [Michael Palin]
dtype: object
"""
常用统计方法
方法 | 功能 |
---|---|
s1.sum() | 求和 |
s1.cov(s2) | 求协方差 |
s1.max() | 求最大值 |
s1.min() | 求最小值 |
s1.std() | 求标准差 |
s1.corr(s2) | 求相关系数矩阵 |
s1.mean() | 求平均值 |
s1.count() | 统计非空值的个数 |
s1.sort_values() | 按数据排序,默认为升序 |
s1.sort_index() | 按索引排序,默认为升序 |
s1.value_counts() | 统计数据中各不同值出现的次数 |