一、Pandas
- 它是选择以NumPy为基础进行设计,在数据分析中Pandas和NumPy这两个模块经常是一起使用。
Pandas是数据处理和数据分析首选库。
Pandas提供了大量标准数据模型和高效操作大型数据集所需要的函数和方法,
是使得Python能够成为高效且强大的数据分析工具的重要因素之一。
使用Pandas库时,需要导入它并命名别名为pd:
import pandas as pd
二、pandas数据结构
- 1)Series,带标签的一维数组;
2)DatetimeIndex,时间序列;
3)DataFrame,带标签且大小可变的二维表格结构;
4)Panel,带标签且大小可变的三维数组。
三、series对象
-
1)Series:pandas提供类似于一维数组的字典结构的对象,用于存储一行或一列的数据。
2)Series对象的内部结构是由两个相互关联的数组组成,其中用于存放数据(即值)的是value主数组,
主数组的每个元素都有一个与之相关联的标签(即索引),这些标签存储在另外一个叫做Index的数组中。
3)如果在创建时没有明确指定索引则会自动使用从0开始的非负整数作为索引。
4)pd.Series(data=None, index=None, dtype=None, name=None, copy=False) -
data:产生序列的数据,可以是ndarray、list或字典
index:设置索引,索引值的个数与需与data数据的长度相同。若省略index参数,其索引0, 1, 2, …。
dtype:序列元素的数据类型,若省略pandas以数据的类型推断数据类型。
name:序列的名称
copy:复制数据,产生数据副本。默认值是false
'''
1.Series对象的创建
(1)使用列表创建Series
Series([数据1, 数据2,…],index=[索引1, 索引2,…])
若省略index,则自动添加索引
'''
import pandas as pd
slist1 = pd.Series([1, 2, 3, 4])
#自动添加索引,索引从0开始
slist2 = pd.Series([1,2,3,4],index=['a','b','c','d'])
slist3 = pd.Series([1,2,3,4],[chr(i+65) for i in range(4)])
print(slist1,slist2,slist3,sep='\n')
#(2) 使用range创建Series
#Series(range(strat,stop,step),index=[索引1, 索引2,…])
#省略index,自动添加索引,索引从0开始
srange1 = pd.Series(range(3))
srange2 = pd.Series(range(2,10,3))
srange3 = pd.Series(range(2,10,2),index=[i for i in range(2,10,2) ])
print(srange1,srange2,srange3,sep='\n')
#(3) 使用numpy一维数组创建Series
import numpy as np
snumpy1 = pd.Series(np.array([1, 2, 3, 4]))
snumpy2 = pd.Series(np.arange(6,10))
snumpy3 = pd.Series(np.linspace(20,30,5))
#20-30之间分为5个浮点数
print(snumpy1,snumpy2,snumpy3,sep='\n')
#由数组创建Series时,引用了该对象。
aa = np.array([2,3,4,5])
aas = pd.Series(aa)
aas1 = pd.Series(aa,copy=True)
print(aa,aas,sep='\n')
aa[3] = 999
aas[0] = 1000
print(aa,aas,aas1,sep='\n')
#(4) 使用字典创建Series,其中字典的键就是索引
sdict1 = pd.Series( {'Python程序设计':95,'数据结构':90,'高等数学':88} )#元组
sdict2 = pd.Series(dict(python编程=92,高等数学=89,数据结构=96)) #转换为元组->索引
print(sdict1,sdict2,sep='\n')
# 2.Series 的值与索引的查看
# 利用values和index可查看Series值和标签
print(sdict1.index)
print(sdict1.values)
print(slist2.index)
print(sdict2.values)
# 3.通过索引或切片访问与修改Series的值
sdict1 = pd.Series({'python程序设计':85,'数据结构':87,'高等数学':78})
print('\n','sdict1原始数据'.center(20, '='))
print(sdict1)
sdict1['python程序设计']=98
# 修改数据的方法
print('\n',"修改sdict1['python程序设计']=89后数据".center(30, '='))
print(sdict1)
sdict1['大学英语']=87 #若该索引不存在,则增加该数据
print('\n','sdict1增加后数据'.center(20, '='))
print(sdict1)
# 也可采用默认的索引进行修改与访问
sdict1[0:2]=0 #采用切片的形式进行局部修改
sdict1[3]=999
print('\n','sdict1[0:2]=0 切片修改sdict1[3]=999索引修改后数据'.center(40, '='),sdict1,sep='\n')
# 4.Series对象间的运算
#(1)算术运算与数学函数运算
ss = pd.Series(np.linspace(-2,2,4))
print('\n','ss原数据'.center(14, '='),ss,sep='\n')
print('\n','对ss所有数据求绝对值,保留3位小数'.center(20, '='),round(abs(ss),3),sep='\n')
print(np.sqrt(abs(ss)))
# round() 方法返回浮点数x的四舍五入值。它的的语法:round( x [, n] )
# 参数:x -- 数值表达式;n -- 数值表达式,表示从小数点位数。
# abs函求绝对值
print('\n','ss的算术运算'.center(14, '='))
print('加+5:',ss+5,'减-5:',ss-5,'乘*5',ss*5,'除/5',ss/5,sep='\n')
# (2)筛选符合条件的元素
ss = pd.Series([np.random.randint(1,50) for i in range(10)])
# 筛选大于25的所有数
ss1 = ss[ss>25]
print('\n',ss,ss1,sep='\n')
# 筛选能被5整除的数
ss2 = ss[ss%5==0]
print('筛选能被5整除的数\n',ss2)
# 筛选出20到30之间的数
print('筛选出20到30之间的数'.center(20,'='))
ss3 = ss[(20<=ss) & (ss<=30)]
print(ss3)
# 筛选出小于20与大于40的数
print('筛选出小于20与大于40的数'.center(20,'='))
ss3 = ss[(40<=ss) | (ss<=20)]
print(ss3)
# (3)修改索引 reset_index(drop=True)
ss_index1 = ss1.reset_index()
print(ss_index1,type(ss_index1))
ss_index2 = ss1.reset_index(drop=True)
#删除原索引
print(ss_index2,type(ss_index2))
# 5.Series对象统计运算
stu1 = pd.Series({'python程序设计':85,'数据结构':87,'高等数学':96,'大学英语':76})
#求最大值的索引与最小值的索引
print('stu1最大值的索引'.center(20, '='))
print(stu1.idxmax())
print('stu1最小值的索引'.center(20, '='))
print(stu1.idxmin())
# 求均值 mean()
print('\n均值:',stu1.mean())
print('stu1中大于平均值的数据'.center(30,'='))
stu_mean=stu1[stu1>stu1.mean()]
print(stu_mean)
#判断元素是否存在 isin()
nn = [i for i in range(80,90)]
nn1 = stu1.isin(nn)
# 它的返回值是 True or False
print('以bool值输出80--89间的数据'.center(30, '='))
print(nn1)
print('只输出bool为True的数据'.center(30, '='))
print(nn1[nn1.values==True]) #输出值为True的数据
nn1_index = nn1[nn1.values==True].index
print('输出True的数据的索引'.center(30, '='))
print(nn1_index)
print(list(nn1_index))
# 项目分析
import pandas as pd
num = pd.Series([np.random.randint(1,10) for i in range(20)])
print('\n原Series\n',num)
#将Series中的重复元素删除,去重。
print('将Series中元素去重 unique()'.center(30,'='))
print(num.unique())
#统计元素出现的次数 value_counts()
print('统计元素出现的次数 value_counts()'.center(30,'='))
print(num.value_counts())
#进行排序,按值排序 sort_values(ascending=True),默认按升序排序,原Series不变
print('按值排序 sort_values()'.center(30,'='))
print(num.sort_values())
#按值排序 sort_values(ascending=False),按降序排序,原Series不变
print('按值排序 sort_values(ascending=False)'.center(30,'='))
print(num.sort_values(ascending=False))
运行结果如下:
-
0 1
1 2
2 3
3 4
dtype: int64
a 1
b 2
c 3
d 4
dtype: int64
A 1
B 2
C 3
D 4
dtype: int64
0 0
1 1
2 2
dtype: int64
0 2
1 5
2 8
dtype: int64
2 2
4 4
6 6
8 8
dtype: int64
0 1
1 2
2 3
3 4
dtype: int32
0 6
1 7
2 8
3 9
dtype: int32
0 20.0
1 22.5
2 25.0
3 27.5
4 30.0
dtype: float64
[2 3 4 5]
0 2
1 3
2 4
3 5
dtype: int32
[1000 3 4 999]
0 1000
1 3
2 4
3 999
dtype: int32
0 2
1 3
2 4
3 5
dtype: int32
Python程序设计 95
数据结构 90
高等数学 88
dtype: int64
python编程 92
高等数学 89
数据结构 96
dtype: int64
Index([‘Python程序设计’, ‘数据结构’, ‘高等数学’], dtype=‘object’)
[95 90 88]
Index([‘a’, ‘b’, ‘c’, ‘d’], dtype=‘object’)
[92 89 96] -
=sdict1原始数据=
python程序设计 85
数据结构 87
高等数学 78
dtype: int64 -
=修改sdict1[‘python程序设计’]=89后数据=
python程序设计 98
数据结构 87
高等数学 78
dtype: int64 -
sdict1增加后数据=
python程序设计 98
数据结构 87
高等数学 78
大学英语 87
dtype: int64 -
=sdict1[0:2]=0 切片修改sdict1[3]=999索引修改后数据=
python程序设计 0
数据结构 0
高等数学 78
大学英语 999
dtype: int64 -
ss原数据=
0 -2.000000
1 -0.666667
2 0.666667
3 2.000000
dtype: float64 -
=对ss所有数据求绝对值,保留3位小数=
0 2.000
1 0.667
2 0.667
3 2.000
dtype: float64
0 1.414214
1 0.816497
2 0.816497
3 1.414214
dtype: float64 -
=ss的算术运算==
加+5:
0 3.000000
1 4.333333
2 5.666667
3 7.000000
dtype: float64
减-5:
0 -7.000000
1 -5.666667
2 -4.333333
3 -3.000000
dtype: float64
乘*5
0 -10.000000
1 -3.333333
2 3.333333
3 10.000000
dtype: float64
除/5
0 -0.400000
1 -0.133333
2 0.133333
3 0.400000
dtype: float64 -
0 28
1 29
2 33
3 25
4 21
5 46
6 17
7 13
8 13
9 20
dtype: int64
0 28
1 29
2 33
5 46
dtype: int64
筛选能被5整除的数
3 25
9 20
dtype: int64
筛选出20到30之间的数
0 28
1 29
3 25
4 21
9 20
dtype: int64
=筛选出小于20与大于40的数=
5 46
6 17
7 13
8 13
9 20
dtype: int64
index 0
0 0 28
1 1 29
2 2 33
3 5 46 <class ‘pandas.core.frame.DataFrame’>
0 28
1 29
2 33
3 46
dtype: int64 <class ‘pandas.core.series.Series’>
=stu1最大值的索引=
高等数学
=stu1最小值的索引=
大学英语 -
均值: 86.0
stu1中大于平均值的数据=
数据结构 87
高等数学 96
dtype: int64
以bool值输出80–89间的数据
python程序设计 True
数据结构 True
高等数学 False
大学英语 False
dtype: bool
=只输出bool为True的数据==
python程序设计 True
数据结构 True
dtype: bool
=输出True的数据的索引=
Index([‘python程序设计’, ‘数据结构’], dtype=‘object’)
[‘python程序设计’, ‘数据结构’] -
原Series
0 4
1 7
2 4
3 5
4 1
5 1
6 5
7 8
8 6
9 7
10 4
11 8
12 9
13 1
14 6
15 5
16 6
17 7
18 2
19 1
dtype: int64
将Series中元素去重 unique()=
[4 7 5 1 8 6 9 2]
=统计元素出现的次数 value_counts()=
1 4
7 3
6 3
5 3
4 3
8 2
9 1
2 1
dtype: int64
按值排序 sort_values()
19 1
13 1
4 1
5 1
18 2
10 4
0 4
2 4
3 5
15 5
6 5
8 6
14 6
16 6
1 7
17 7
9 7
7 8
11 8
12 9
dtype: int64
按值排序 sort_values(ascending=False)
12 9
11 8
7 8
9 7
17 7
1 7
16 6
14 6
8 6
6 5
15 5
3 5
2 4
0 4
10 4
18 2
5 1
4 1
13 1
19 1
dtype: int64