一、导入
from pandas import Series
import pandas as pd#注意着两个导入的先后顺序
二、示例
2.1 初始化
Series相当于一个一维数组,Series显示时的一大好处就是会自动对齐
传入一个list,index默认为0~N-1
注意a.values的s不要忘记
In [5]: a=Series(['a','b','c','d'])
In [6]: a
Out[6]:
0 a
1 b
2 c
3 d
dtype: object
In [7]: a.index
Out[7]: RangeIndex(start=0, stop=4, step=1)
In [8]: a.values
Out[8]: array(['a', 'b', 'c', 'd'], dtype=object)
传入index
In [26]: b=Series(list(range(4)),index=[1,2,'c','d'])
In [27]: b
Out[27]:
1 0
2 1
c 2
d 3
dtype: int64
2.2 利用下标索引
In[28]: b[1]
Out[28]: 0
In[29]: b['c']
Out[29]: 2
In[30]: b[3]
Out[30]: 3
In[31]: b[0]
Out[31]: 0
我发现就算初始化时指定了索引,但是仍然可以用默认的索引,只有找不到指定索引才会看看默认索引是否适用
也可以一次多次索引,仍然传入一个索引的list进去
In[32]: b[[2,'c']]
Out[32]:
2 1
c 2
dtype: int64
2.3 运算
Series运算时针对每个value的运算,运算结束后保持value与index的不变性
注意判断单个元素里面必须写b[b>2]的格式。相当于选择了b>2的True部分
In[41]: b>2
Out[41]:
1 False
2 False
c False
d True
dtype: bool
In[42]: b[b>2]
Out[42]:
d 3
dtype: int64
In[43]: b[c>2]
Traceback (most recent call last):
File "<ipython-input-43-313c9b8716f8>", line 1, in <module>
b[c>2]
NameError: name 'c' is not defined
判断是否为空
b.isnull()
Out[64]:
1 False
2 False
c False
d False
dtype: bool
pd.notnull(b)
Out[66]:
1 True
2 True
c True
d True
dtype: bool
pd.isnull(b)
Out[67]:
1 False
2 False
c False
d False
dtype: bool
Series运算后的结果总是Series,就算这是一个空的Series
w=Series()
w
Out[69]: Series([], dtype: float64)
w.isnull()
Out[70]: Series([], dtype: bool)
2.4 与字典的关系
由于可以把Series看成一个index与value对应的有序字典OrderedDict,就是index到value的映射。所以一些适用于字典的方法也适合Series
1.检查索引是否存在
In[49]: 'c' in b
Out[49]: True
Out[50]: 0 in b
Out[50]: False
2.通过字典初始化
In[51]: c={'a':1,'b':2,'c':3,'d':4}
In[52]: c=Series(c)
In[53]: c
Out[53]:
a 1
b 2
c 3
d 4
dtype: int64
传入dict和index
index=['a1','b','c','d1']
c={'a':1,'b':2,'c':3,'d':4}
d=Series(c,index)
d
Out[58]:
a1 NaN
b 2.0
c 3.0
d1 NaN
dtype: float64
c=Series(c)
d=Series(c,index)
d
Out[61]:
a1 NaN
b 2.0
c 3.0
d1 NaN
dtype: float64
2.5 Series之间运算
b=Series(list(range(4)),index=['a','b','c','d'])
c=Series(list(range(4)),index=['a','b','e','f'])
b
Out[82]:
a 0
b 1
c 2
d 3
dtype: int64
c
Out[83]:
a 0
b 1
e 2
f 3
dtype: int64
合并所有的索引,如果两个都有就相加,否则为缺失
b+c
Out[84]:
a 0.0
b 2.0
c NaN
d NaN
e NaN
f NaN
dtype: float64
b-c
Out[85]:
a 0.0
b 0.0
c NaN
d NaN
e NaN
f NaN
dtype: float64
2.6 属性
指定Series名字
b.name='b'
b
Out[87]:
a 0
b 1
c 2
d 3
Name: b, dtype: int64
指定index
b.index=['v','d','x','w']
b
Out[89]:
v 0
d 1
x 2
w 3
Name: b, dtype: int64
指定value
b['v']=9
b
Out[91]:
v 9
d 1
x 2
w 3
Name: b, dtype: int64
b.value=[12,3,21,4]
b
Out[93]:
v 9
d 1
x 2
w 3
Name: b, dtype: int64