Pandas模块
1.非常强大的python数据分析包
2.基于numpy构建的 所以你学习起来会有一种似曾相识的感觉
3.pandas奠定了python在数据分析领域的一哥地位
主要功能
1 具有两大非常灵活强大的数据类型
Series
DataFrame
2.集成时间模块
3.提供丰富的数学运算和操作(基于Numpy)
4.针对缺失数据操作非常灵活
导入方法
导入pandas,约定俗成的导入语句书写
import pandas as pd
数据结构之Series
是一种类似于一维数组对象,由数据和相关的标签(索引)组成
Series的结构
左侧是标签
右侧是数据
Series的创建方式总共有四种
# 第一种
# Series的创建
res = pd.Series([111,222,333,444,555])
res
# 默认会自动帮你用索引作为数据的标签
# 第二种
# 指定元素的标签:个数一定要一致
res1 = pd.Series([111,222,333,444,555],index=['a','b','c','d','e'])
res1
# 第三种
# 直接放字典
res2 = pd.Series({
'username':'abc',
'password':123,
'hobby':'read'
})
res2
# 第四种
pd.Series(0,index=['a','b','c'])
执行结果:
a 0
b 0
c 0
dtype: int64
缺失数据处理
isnull 判断是否缺失,是缺失值返回True
notnull 判断是否缺失,不是缺失值返回True
# 过滤缺失值 布尔型索引
obj[obj.notnull()]
dropna 删除缺失数据
fillna 填充缺失数据
# 默认也是不修改原来的数据 要想直接修改加参数inplace=True即可
Series的各种特性
基本跟Numpy操作一致
1.ndarray直接创建Series:Series(array)
Series可以直接将numpy中的一维数组转换(这里必须只能是一维)
res = pd.Series(np.array([1,2,3,4,5,6]))
res
2.与标量运算
res = pd.Series([1,2,3,4,5])
res * 2
0 2
1 4
2 6
3 8
4 10
dtype: int64
3.两个Series运算
res * res
0 1
1 4
2 9
3 16
4 25
dtype: int64
res1 = pd.Series([1,2,3,4],index=['a','b','c','d'])
res * res1
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
a NaN
b NaN
c NaN
d NaN
dtype: float64
4.通用函数abs
res3 = pd.Series([-1,-2,-3,-4,5,6])
res3.abs()
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
5.布尔值索引
res[res.notnull()]
6.统计函数
7.从字典创建Series:Series(dic)
res4 = pd.Series({'username':'abc','password':123})
res4
8.In运算
'username' in res4
True
'username' in res4 # 跟python中的字典不一样 这里直接拿数据而不是标签
print(i)
abc
123
9.键索引与切片
10.其他函数等
布尔选择器
import numpy as np
import pandas as pd
mask = pd.Series([True,False,False,True,False])
price = pd.Series([321312,123,324,5654,645])
# 掌握
price[mask]
0 321312
3 5654
dtype: int64
# 了解
price|mask
0 True
1 True
2 True
3 True
4 True
dtype: bool
price&mask
0 False
1 False
2 False
3 False
4 False
dtype: bool
# 需要掌握
(price > 100) & (price < 700)
0 False
1 True
2 True
3 False
4 True
dtype: bool
price[(price > 100) & (price < 700)]
1 123
2 324
4 645
dtype: int64
索引及标签
res = pd.Series({'a':111,'b':222,'c':333,'d':444,'e':555})
一般情况下可以使用两种方式
# 索引取值
res[0]
111
# 标签取值
res['a']
111
# 获取所有的标签
res.index
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
# 给标签加列名称
res.index.name = 'ZBC'
res
ZBC
a 111
b 222
c 333
d 444
e 555
dtype: int64
# 整数索引
sr = pd.Series(np.arange(6))
sr
0 0
1 1
2 2
3 3
4 4
5 5
dtype: int32
res1 = sr[3:]
res1
3 3
4 4
5 5
dtype: int32
# 索引取值
# res1[1] # 报错
'''针对取值操作,以后需要用特定的方法来约束'''
# iloc按照索引的方式取值
# loc按照标签的方式取值
# res1.iloc[1] # 1
#res1.loc[3] # 3
'''非常重要,一定要记忆'''
日期类型
# date_range时间间隔
res1 = pd.date_range('2020-01-01','2020-06-01',freq='M') # frep后面按照指定的时间间隔
res1
DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30',
'2020-05-31'],
dtype='datetime64[ns]', freq='M')
# 还可以将日期作为Series的标签
res2 = pd.Series([111,222,333,444,555],index=res1)
res2
2020-01-31 111
2020-02-29 222
2020-03-31 333
2020-04-30 444
2020-05-31 555
Freq: M, dtype: int64
数据对齐
sr1 = pd.Series([12,23,34], index=['c','a','d'])
sr2 = pd.Series([11,20,10], index=['d','c','a',])
sr1 + sr2
运行结果:
a 33
c 32
d 45
dtype: int64
# 可以通过这种索引对齐直接将两个Series对象进行运算
sr3 = pd.Series([11,20,10,14], index=['d','c','a','b'])
sr1 + sr3
运行结果:
a 33.0
b NaN
c 32.0
d 45.0
dtype: float64
# sr1 和 sr3的索引不一致,所以最终的运行会发现b索引对应的值无法运算,就返回了NaN,一个缺失值
# 因为NaN其实是float类型,所以int64变成float64。(type(np.nan) 结果是:float)
数据操作
# 查
res.loc['a']
# 改
res.iloc[2] = 100
# 增
# 方式1:append不修改原数据
res.append(pd.Series([66],index=['e']))
# 方式2:set_value直接修改原数据
res.set_value('f',999) # 会有一个提示 如果不想有这个提示需要修改配置
# 删:del关键字作用的也是原数据
del res['f']
灵活的算术方法
"""
针对加减乘除等数学运算
可以直接使用符号
也可以使用提供的方法名(可以有额外的功能)
add
sub
div
mul
"""
sr1 = pd.Series([12,23,34], index=['c','a','d'])
sr2 = pd.Series([11,20,10,14], index=['d','c','a','b'])
sr1.add(sr2,fill_value=0)
运行结果:
a 33.0
b 14.0
c 32.0
d 45.0
dtype: float64
# 将缺失值设为0,所以最后算出来b索引对应的结果为14
'''
在计算之前对即将要计算的数据进行缺失值的处理再运算
避免数据不准确的问题
'''