Pandas-存储数据结构之Series

259 阅读2分钟

import pandas as pd
pd.Series(data, index=index)

Series是一维带标签的数组,可以存储所有的数据类型,像整型数据,字符串,浮点数和Python的对象。Pandas数据的轴标签在Series上表现就是它的index。数据可以是:

python字典
ndarray数据
标量

ndarrary数据

ndarrary数据的index和data的长度必须要一致,index属性可以缺省,缺省的时候用从0-len(data)-1的数字进行代替。

import numpy as np
import pandas as pd
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
s
Out[6]: 
a    0.565226
b    1.006869
c   -1.098245
d   -0.854473
e   -0.672521
dtype: float64

s=pd.Series(np.random.randn(5))
s
Out[8]: 
0   -0.845398
1    0.163017
2   -0.965521
3   -0.357812
4   -0.512527
dtype: float64

字典类型

如果在传递字典类型的参数时候,index缺省,那么index就会使用字典的键值;否则不使用键值。

d = {'a': 0., 'b': 1., 'c': 2.}
pd.Series(d)
Out[10]: 
a    0.0
b    1.0
c    2.0
dtype: float64
pd.Series(d, index=['b', 'c', 'd', 'a'])
Out[11]: 
b    1.0
c    2.0
d    NaN
a    0.0
dtype: float64

标量

如果index的数量多于一个,那么标量会自动复制。

pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])
Out[12]: 
a    5.0
b    5.0
c    5.0
d    5.0
e    5.0
dtype: float64

Series是一种类ndarray的对象,对于很多数组函数来说,Series也是一个有效的参数;数组分片对于Series也是同样适用。

对于上面创建的Series对象s:

s[0]
Out[13]: -0.8453984517211155
s[:3]
Out[14]: 
0   -0.845398
1    0.163017
2   -0.965521
dtype: float64
s[s>s.median()]
Out[15]: 
1    0.163017
3   -0.357812
dtype: float64


很多数组的方法对于Series对象都是适用的。Series对象也可以一一对应转化为数组,使用的方法是Series.array

s.array
Out[17]: 
<PandasArray>
[-0.8453984517211155, 0.16301681608073876, -0.9655209402225259,
 -0.3578118719653499, -0.5125266763578133]
Length: 5, dtype: float64

同样,Series对象是类ndarray对象,它可以转化为ndarray对象,使用的方法是:Series.to_numpy(),返回一个Numpy的ndarray对象。Series对象也可以像字典类型一样使用键值进行数据的访问。