北理工嵩天老师的慕课课程 《python数据分析与展示》学习笔记!
1. Pandas库的介绍
Pandas是Python第三方库,提供高性能易用数据类型和分析工具。
Pandas基于Numpy实现,常与Numpy和Matplotlib一同使用。
Pandas 主要提供两个数据类型: Series,DataFrame
import pandas as pd
Pandas和Numpy的区别:
Numpy | Pandas |
---|---|
基础数据类型 | 扩展数据类型 |
关注数据的结构表达 | 关注数据的应用表达 |
维度:数据间关系 | 数据与索引间关系 |
2. Pandas库的Series类型
Series类型由一组数据及相关的数据索引组成。
2.1 Series类型的创建
(1)从列表创建
>>> import pandas as pd
>>> a = pd.Series([9,8,7,6])
>>> a
0 9
1 8
2 7
3 6
dtype: int64
如上例,Series类型会自动为数据(第二列)增加索引(第一列),索引与数据之间一一对应。
同时,也可以自定义索引,如下例,若index作为第二个参数,也可省略“index=”。
>>> import pandas as pd
>>> pd.Series([9,8,7,6], index=['a','b','c','d'])
a 9
b 8
c 7
d 6
dtype: int64
(2)从标量值创建
>>> import pandas as pd
>>> a = pd.Series(25, index=['a','b','c'])
>>> a
a 25
b 25
c 25
dtype: int64
(3)从字典类型创建
>>> import pandas as pd
>>> b = pd.Series({'a':9, 'b':8, 'c':7})
>>> b
a 9
b 8
c 7
dtype: int64
使用字典创建Series时,Pandas将字典的所有“键”值变成了对应值的索引。
但是也可以使用index构建不同的Series类型。
>>> import pandas as pd
>>> c = pd.Series({'a':9, 'b':8, 'c':7}, index=['c','a','b','d'])
>>> c
c 7.0
a 9.0
b 8.0
d NaN
dtype: float64
(4)从ndarray类型创建
>>> import numpy as np
>>> import pandas as pd
>>> d = pd.Series(np.arange(5), index=np.arange(9,4,-1))
>>> d
9 0
8 1
7 2
6 3
5 4
dtype: int32
此外,也可以通过其他函数创建,比如range()。
2.2 Series类型的基本操作
(1)获取所有索引和数据
.index 获得索引
.values 获得数据
>>> import pandas as pd
>>> b = pd.Series([9,8,7,6],['a','b','c','d'])
>>> b
a 9
b 8
c 7
d 6
dtype: int64
>>> b.index
Index(['a', 'b', 'c', 'd'], dtype='object')
>>> b.values
array([9, 8, 7, 6], dtype=int64)
(2)获取指定索引的元素值
自动索引和自定义索引并存!但是不能混合使用!
>>> import pandas as pd
>>> b = pd.Series([9,8,7,6],['a','b','c','d'])
>>> b[['c','d',0]]
c 7.0
d 6.0
0 NaN
>>> b[['c','d','a']]
c 7
d 6
a 9
dtype: int64
(3)Series类型的操作类似于ndarray类型
- 索引方法相同,采用[]
- Numpy中运算和操作可用于Series类型
- 可以通过自定义索引的列表进行切片
- 可以通过自动索引进行切片,如果存在自定义索引,则一同被切片
>>> import pandas as pd
>>> a = pd.Series([9,8,7,6],['a','b','c','d'])
>>> a
a 9
b 8
c 7
d 6
dtype: int64
> # 切片
>>> a[:3]
a 9
b 8
c 7
dtype: int64
>>> a[a>a.median()]
a 9
b 8
dtype: int64
> # 判断自定义索引是否在series中
>>> 'c' in a
True
> # 从a中返回索引为‘f’的值,若不存在,则返回100
>>> a.get('f',100)
100
(4)Series类型的对齐操作
Series类型在运算中会自动对齐不同索引的数据
>>> a = pd.Series([9,8,7,6],['a','b','c','d'])
>>> b = pd.Series([1,2,3],['c','d','e'])
>>> a+b
a NaN
b NaN
c 8.0
d 8.0
e NaN
dtype: float64
(5)Series类型的name属性
Series对象和索引都可以有一个名字,存储在属性 .name中
>>> a = pd.Series([9,8,7,6],['a','b','c','d'])
>>> a.name = 'Series对象'
>>> a.index.name = '索引列'
>>> a
索引列
a 9
b 8
c 7
d 6
Name: Series对象, dtype: int64
(6)Series类型的修改
Series对象可以随时修改并即刻生效
>>> a = pd.Series([9,8,7,6],['a','b','c','d'])
>>> a['b','c'] = 20
>>> a
a 9
b 20
c 20
d 6
dtype: int64
3. Pandas库的DataFrame类型
DataFrame是二维带“标签”数组,由共用相同索引的一组列组成。
- DataFrame是一个表格型的数据类型,每列值类型可以不同
- DataFrame既有行索引,也有列索引
- DataFrame常用于表达二维数据,但可以表达多维数据
3.1 DataFrame创建
(1) 从二维ndarray对象创建
在创建DataFrame类型时,会自动加上行索引和列索引。
>>> import pandas as pd
>>> import numpy as np
>>> a = pd.DataFrame(np.arange(10).reshape(2,5))
>>> a
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
(2) 从一维ndarray对象字典创建
>>> dt = {'one': pd.Series([1,2,3], index=['a','b','c']), 'two': pd.Series([9,8,7,6], index=['a','b','c','d'])}
>>> d = pd.DataFrame(dt)
>>> d
one two
a 1.0 9
b 2.0 8
c 3.0 7
d NaN 6
> # 规定行列索引
>>> pd.DataFrame(dt, index=['b','c'],columns=['two','four'])
two four
b 8 NaN
c 7 NaN
(3) 从列表类型字典创建
>>> d1 = {'one':[1,2,3,4], 'two':[9,8,7,6]}
>>> d = pd.DataFrame(d1, index=['a','b','c','d'])
>>> d
one two
a 1 9
b 2 8
c 3 7
d 4 6
3.2 DataFrame获取指定索引的元素
>>> d1 = {'type1':['a','b','c','d'], 'type2':[1,2,3,4], 'type3':[51,52,53,54], 'type4':[101,102,103,104]}
>>> d = pd.DataFrame(d1,index=['c1','c2','c3','c4'])
>>> d
type1 type2 type3 type4
c1 a 1 51 101
c2 b 2 52 102
c3 c 3 53 103
c4 d 4 54 104
根据上述创建的DataFrame类型,获取指定索引元素的操作为:
> # 获取一列
>>> d['type1']
c1 a
c2 b
c3 c
c4 d
Name: type1, dtype: object
> # 获取一行
>>> d.ix['c2']
type1 b
type2 2
type3 52
type4 102
Name: c2, dtype: object
> # 获取指定位置
>>> d['type1']['c1']
'a'
4. Pandas库的数据类型操作
4.1 重新索引
.reindex() 能够改变或重排Series和DataFrame索引。
>>> d1 = {'type1':['a','b','c','d'], 'type2':[1,2,3,4], 'type3':[51,52,53,54], 'type4':[101,102,103,104]}
>>> d = pd.DataFrame(d1,index=['c1','c2','c3','c4'])
>>> d
type1 type2 type3 type4
c1 a 1 51 101
c2 b 2 52 102
c3 c 3 53 103
c4 d 4 54 104
同样使用该DataFrame类型进行测试:
>>> d = d.reindex(index=['c4','c3','c2','c1'])
>>> d
type1 type2 type3 type4
c4 d 4 54 104
c3 c 3 53 103
c2 b 2 52 102
c1 a 1 51 101
>>> d = d.reindex(columns=['type4','type3','type2','typeeeee'])
>>> d
type4 type3 type2 typeeeee
c4 104 54 4 NaN
c3 103 53 3 NaN
c2 102 52 2 NaN
c1 101 51 1 NaN
参数 | 说明 |
---|---|
index, columns | 新的行列自定义索引 |
fill_value | 重新索引中,用于填充缺失位置的值 |
method | 填充方法,ffill当前值向前填充,bfill向后填充 |
limit | 最大填充量 |
copy | 默认True,生成新的对象,False时,新旧相等不复制 |
>>> newd = d.columns.insert(4,'newtype')
>>> newd
Index(['type1', 'type2', 'type3', 'type4', 'newtype'], dtype='object')
>>> new = d.reindex(columns=newd, fill_value=200)
>>> new
type1 type2 type3 type4 newtype
c1 a 1 51 101 200
c2 b 2 52 102 200
c3 c 3 53 103 200
c4 d 4 54 104 200
4.2 索引类型
>>> d.index
Index(['c1', 'c2', 'c3', 'c4'], dtype='object')
>>> d.columns
Index(['type1', 'type2', 'type3', 'type4'], dtype='object')
Series和DataFrame的索引是Index类型
索引类型 的常用方法(不是DataFrame的方法,而是index或columns的方法 ):
方法 | 说明 |
---|---|
.append(idx) | 连接另一个index对象,产生新的index对象 |
.diff(idx) | 计算差集,产生新的index对象 |
.intersection(idx) | 计算交集 |
.union(idx) | 就算并集 |
.delete(loc) | 删除loc位置处的元素 |
.insert(loc, e) | 在loc位置增加一个元素e |
>>> d
type1 type2 type3 type4
c1 a 1 51 101
c2 b 2 52 102
c3 c 3 53 103
c4 d 4 54 104
>>> nc = d.columns.delete(2) # 列索引删除位置2处
>>> ni = d.index.insert(5,'c5') # 列索引在位置5处添加‘c5’
>>> nd = d.reindex(index=ni, columns=nc, method='ffill') # 向前填充
>>> nd
type1 type2 type4
c1 a 1 101
c2 b 2 102
c3 c 3 103
c4 d 4 104
c5 d 4 104
4.3 删除指定索引对象
.drop() 能够删除Series和DataFrame指定行或列索引。
>>> d
type1 type2 type3 type4
c1 a 1 51 101
c2 b 2 52 102
c3 c 3 53 103
c4 d 4 54 104
> # drop默认操作0轴上的元素(因为Series只有0轴!!!~~~~~)
>>> d.drop('c4')
type1 type2 type3 type4
c1 a 1 51 101
c2 b 2 52 102
c3 c 3 53 103
> # 删除某一列时,要添加“axis=1”,表示删除1轴上的
>>> d.drop('type4',axis=1)
type1 type2 type3
c1 a 1 51
c2 b 2 52
c3 c 3 53
c4 d 4 54
5. Pandas库的数据类型计算
5.1 数据类型的算数运算
算术运算法则:
- 算数运算根据行列索引,补齐后运算,运算默认产生浮点数
- 补齐时缺项填充NaN(空值)
- 二维和一维、一维和零维间为广播运算
- 采用±*/符号进行二元运算产生新的对象
(1) 符号运算
>>> a = pd.DataFrame(np.arange(12).reshape(3,4))
>>> a
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
>>> b = pd.DataFrame(np.arange(20).reshape(4,5))
>>> b
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
> # 标签相同的行和列直接运算,标签不同的行和列补齐后运算!
>>> a+b
0 1 2 3 4
0 0.0 2.0 4.0 6.0 NaN
1 9.0 11.0 13.0 15.0 NaN
2 18.0 20.0 22.0 24.0 NaN
3 NaN NaN NaN NaN NaN
>>> a * b
0 1 2 3 4
0 0.0 1.0 4.0 9.0 NaN
1 20.0 30.0 42.0 56.0 NaN
2 80.0 99.0 120.0 143.0 NaN
3 NaN NaN NaN NaN NaN
(2) 方法运算
除使用符号进行算数运算外,也可以采用方法进行运算:
方法 | 说明 |
---|---|
.add(d, **argws) | 类型间加法运算,可选参数 |
.sub(d, **argws) | 类型间减法运算,可选参数 |
.mul(d, **argws) | 类型间乘法运算,可选参数 |
.div(d, **argws) | 类型间除法运算,可选参数 |
>>> b.add(a, fill_value=100) # 使用100补齐!
0 1 2 3 4
0 0.0 2.0 4.0 6.0 104.0
1 9.0 11.0 13.0 15.0 109.0
2 18.0 20.0 22.0 24.0 114.0
3 115.0 116.0 117.0 118.0 119.0
>>> a.mul(b, fill_value=0)
0 1 2 3 4
0 0.0 1.0 4.0 9.0 0.0
1 20.0 30.0 42.0 56.0 0.0
2 80.0 99.0 120.0 143.0 0.0
3 0.0 0.0 0.0 0.0 0.0
(3) 不同维度间运算
不同维度间的运算采用广播运算,默认发生在1轴(这里要好好理解)!
>>> import numpy as np
>>> import pandas as pd
>>> b = pd.DataFrame(np.arange(20).reshape(4,5))
>>> b
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
>>> c = pd.Series(np.arange(4))
>>> c
0 0
1 1
2 2
3 3
dtype: int32
>>> c - 10
0 -10
1 -9
2 -8
3 -7
> # 二维和一维进行运算,默认发生在1轴上,即b的每一行都被操作。
>>> b - c
0 1 2 3 4
0 0.0 0.0 0.0 0.0 NaN
1 5.0 5.0 5.0 5.0 NaN
2 10.0 10.0 10.0 10.0 NaN
3 15.0 15.0 15.0 15.0 NaN
> # 设置运算发生在0轴上,要通过“axis=0”
>>> b.sub(c,axis=0)
0 1 2 3 4
0 0 1 2 3 4
1 4 5 6 7 8
2 8 9 10 11 12
3 12 13 14 15 16
5.2 数据类型的比较运算
比较运算的法则:
- 比较运算只能比较相同索引的元素,不进行补齐
- 二维和一维、一维和零维间为广播运算
- 采用> < >= <= == != 等符号进行二元运算产生布尔对象
(1) 相同维度的比较
>>> a = pd.DataFrame(np.arange(12).reshape(3,4))
>>> a
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
>>> d = pd.DataFrame(np.arange(12,0,-1).reshape(3,4))
>>> d
0 1 2 3
0 12 11 10 9
1 8 7 6 5
2 4 3 2 1
>>> a>d
0 1 2 3
0 False False False False
1 False False False True
2 True True True True
>>> a == d
0 1 2 3
0 False False False False
1 False False True False
2 False False False False
(2) 不同维度的比较
>>> a = pd.DataFrame(np.arange(12).reshape(3,4))
>>>> a
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
>>> c = pd.Series(np.arange(4))
>>> c
0 0
1 1
2 2
3 3
dtype: int32
>>> a > c
0 1 2 3
0 False False False False
1 True True True True
2 True True True True
>>> c > 0
0 False
1 True
2 True
3 True
dtype: bool