Series 可以保存任何数据类型,比如整数、字符串、浮点数、Python 对象等,它的标签默认为整数,从 0 开始依次递增。
创建Series对象
pd.Series( data, index, dtype, copy)
| 参数名称 | 描述 |
|---|---|
| data | 输入的数据,可以是列表、常量、ndarray 数组等。 |
| index | 索引值必须是惟一的,如果没有传递索引,则默认为 np.arrange(n)。 |
| dtype | dtype表示数据类型,如果没有提供,则会自动判断得出。 |
| copy | 表示对 data 进行拷贝,默认为 False。 |
1) 创建一个空Series对象
pd.Series() 输出为空: Series([], dtype: float64)
2) ndarray创建Series对象
ndarray 是 NumPy 中的数组类型,当 data 是 ndarry 时,传递的索引必须具有与数组相同的长度。假如没有给 index 参数传参,在默认情况下,索引值将使用是 range(n) 生成,其中 n 代表数组长度,如下所示:
data = np.array(['a','b','c','d']) py.Series(data) 0 a 1 b 2 c 3 d dtype: object
上述示例中没有传递任何索引,所以索引默认从 0 开始分配 ,其索引范围为 0 到len(data)-1,即 0 到 3。这种设置方式被称为“隐式索引”。
你也可以使用“显式索引”的方法定义索引标签,示例如下:
data = np.array(['a','b','c','d']) 自定义索引标签(即显示索引) pd.Series(data,index=[100,101,102,103]) 100 a 101 b 102 c 103 d dtype: object
3) dict创建Series对象
您可以把 dict 作为输入数据。如果没有传入索引时会按照字典的键来构造索引(data(keys) = index);反之,当传递了索引时需要将索引标签与字典中的值一一对应;
示例1,没有传递索引时:
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
a 0.0
b 1.0
c 2.0
dtype: float64
示例 2,为index参数传递索引时:
data = {'a' : 0., 'b' : 1., 'c' : 2.}
pd.Series(data,index=['b','c','d','a'])
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
当传递的索引值无法找到与其对应的值时,使用 NaN(非数字 | 空)填充。
4) 标量创建Series对象
如果 data 是标量值,则必须提供索引,示例如下:
pd.Series(100, index=[1, 2, 3, 4, 5]) 1 100 2 100 3 100 4 100 5 100 dtype: int64
标量值按照 index 的数量进行重复,并与其一一对应。
访问Series数据
如何访问 Series 序列中元素呢?分为两种方式,一种是位置索引访问;另一种是索引标签访问。
1) 位置索引访问
使用元素自身的下标进行访问
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) print(s[0]) 位置下标 print(s['a']) 标签下标 1 1 切片 s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) print(s[:3]) a 1 b 2 c 3 dtype: int64
2) 索引标签访问
Series 类似于固定大小的 dict,把 index 中的索引标签当做 key,而把 Series 序列中的元素值当做 value,然后通过 index 索引标签来访问或者修改元素值。
s = pd.Series([6,7,8,9,10],index = ['a','b','c','d','e']) print(s['a']) print(s[['a','c','d']]) 6 a 6 c 8 d 9 dtype: int64Series常用属性
| 名称 | 属性 |
|---|---|
| axes | 以列表的形式返回所有行索引标签。 |
| dtype | 返回对象的数据类型。 |
| empty | 返回一个空的 Series 对象。 |
| ndim | 返回输入数据的维数。 |
| size | 返回输入数据的元素数量。 |
| values | 以 ndarray 的形式返回 Series 对象。 |
| index | 返回一个RangeIndex对象,用来描述索引的取值范围。 |
1) axes
[RangeIndex(start=0, stop=5, step=1)]
2) dtype
float64
3) empty
返回一个布尔值,用于判断数据对象是否为空;
4) ndim
查看序列的维数。根据定义,Series 是一维数据结构,因此它始终返回 1。
5) size
返回 Series 对象的大小(长度);
6) values
以数组的形式返回 Series 对象中的数据;
7) index
该属性用来查看 Series 中索引的取值范围。示例如下:
隐式索引: Index(['a', 'b', 'c', 'd'], dtype='object') 显示索引: RangeIndex(start=0, stop=4, step=1)
Series常用方法
1) head()&tail()查看数据
| head() | 默认 return 前5行数据; (n) |
| tail() | 默认 return 后5行数据; (n) |
2) isnull()&nonull()检测缺失值
| isnull() | 如果为值不存在或者缺失,则返回 True。 |
| notnull() | 如果值不存在或者缺失,则返回 False。 |
s=pd.Series([1,2,5,None]) print(pd.isnull(s)) 是空值返回True print(pd.notnull(s)) 空值返回False



