In [11]: obj = pd.Series([4, 7, -5, 3]) In [12]: obj Out[12]: 0 4 1 7 2 -5 3 3 dtype: int64
Series的字符串表现形式为:索引在左边,值在右边。由于我们 没有为数据指定索引,于是会⾃动创建⼀个0到N-1(N为数据的 ⻓度)的整数型索引。还可以设置索引:
In [15]:obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c']) In [16]:obj2 Out[16]: d 4 b 7 a -5 c 3 dtype: int64 In [17]:obj2.values Out[17]:array([ 4, 7, -5, 3], dtype=int64) In [18]:obj2.index Out[18]:Index(['d', 'b', 'a', 'c'], dtype='object')与普通 NumPy 数组相⽐,你可以通过索引的⽅式选取 Series中的单个或⼀组值,就算 使⽤ NumPy 函数或类似 NumPy 的运算(如根据布尔型数组进⾏过滤、标量乘法、应⽤数学函数等)都会保留索引值的链接 :
In [19]: obj2['a'] Out[19]: -5 In [20]: obj2['d']=6 In [21]: obj2[['c','a','d']] Out[21]: c 3 a -5 d 6 dtype: int64 In [22]: obj2*2 Out[22]: d 12 b 14 a -10 c 6 dtype: int64如果数据被存放在⼀个 Python 字典中,也可以直接通过这个字典来创建Series,如若索引值找不到对应的值则会直接补充NaN值:
In [26]: sdata={'Ohio':35000, 'Texas':71000, 'Oregon':16000, 'Utah': 5000}
In [27]: obj3=pd.Series(sdata)
In [28]: obj3
Out[28]:
Ohio 35000
Oregon 16000
Texas 71000
Utah 5000
dtype: int64
查找缺失值时
pandas
的
isnull和notnull
函数可⽤于检测缺失数据。
In [26]: sdata={'California':,'Ohio':35000, 'Texas':71000, 'Oregon':16000, 'Utah': 5000}
In [27]: obj4=pd.Series(sdata)
In [28]: pd.isnull(obj4)
Out[28]:
California True
Ohio False
Oregon False
Texas False
dtype: bool
In [29]: pd.notnull(obj4)
Out[29]:
California False
Ohio True
Oregon True
Texas True
dtype: bool
#Series中的⽅法
In [34]: obj4.isnull()
Out[34]:
California True
Ohio False
Oregon False
Texas False
dtype: bool
Series
对象本身及其索引都有⼀个
name
属性,该属性跟
pandas其他的关键功能关系⾮常密切:
In [38]: obj4.name = 'population' In [39]: obj4.index.name = 'state' In [40]: obj4 Out[40]: state California NaN Ohio 35000.0 Oregon 16000.0 Texas 71000.0 Name: population, dtype: float64Series 的索引还可以通过赋值的⽅式就地修改:
In [41]: obj Out[41]: 0 4 1 7 2 -5 3 3 dtype: int64 In [42]: obj.index=['Bob','Steve','Jeff','Ryan'] In [43]: obj Out[43]: Bob 4 Steve 7 Jeff -5 Ryan 3 dtype: int64



