数据分析三剑客-pandas模块
-
numpy已经可以帮助我们进行数据的处理了,那么学习pandas的目的是什么呢?
-
numpy能够帮助我们处理的是数值型的数据,当然在数据分析中除了数值型的数据还有好多其他类型的数据(字符串,时间序列),那么pandas就可以帮我们很好的处理除了数值型的其他数据!
-
什么是pandas?
-
首先先来认识pandas中的两个常用的类(处理非数值型数据)
-
Series
-
-
Series是一种类似与一维数组的对象,由下面两个部分组成:
-
values:一组数据(ndarray类型)
-
index:相关的数据索引标签
Series的创建
-
由列表或numpy数组创建
-
由字典创建
from pandas import Series s = Series(data=[1,2,3,'four']) s
# 结果 0 1 1 2 2 3 3 four dtype: object import numpy as np s = Series(data=np.random.randint(0,100,size=(3,))) s
# 结果 0 3 1 43 2 82 dtype: int64 #index用来指定显示索引 s = Series(data=[1,2,3,'four'],index=['a','b','c','d']) s
# 结果 a 1 b 2 c 3 d four dtype: object
为什么需要有显示索引
显示索引可以增强Series的可读性
dic = { '语文':100, '数学':99, '理综':250 } s = Series(data=dic) s 语文 100 数学 99 理综 250 dtype: int64
Series的索引和切片
s[0] s.语文 s[0:2]
# 结果 语文 100 数学 99 dtype: int64
Series的常用属性
-
shape
-
size
-
index
-
values
s.shape s.size s.index #返回索引 s.values #返回值 s.dtype #元素的类型
# 结果 dtype('int64') s = Series(data=[1,2,3,'four'],index=['a','b','c','d']) s.dtype #数据类型O表示的是Object(字符串类型) dtype('O')
Series的常用方法
-
head(),tail()
-
unique()
-
isnull(),notnull()
-
add() sub() mul() div()
s = Series(data=np.random.randint(60,100,size=(10,))) s.head(3) #显示前n个数据 s.tail(3) #显示后n个元素
s.unique() #去重 array([99, 88, 74, 72, 80, 63, 85, 70, 76])
s.isnull() #用于判断每一个元素是否为空,为空返回True,否则返回False s.notnull()
Series的算术运算
-
法则:索引一致的元素进行算数运算否则补空
s1 = Series(data=[1,2,3],index=['a','b','c']) s2 = Series(data=[1,2,3],index=['a','d','c']) s = s1 + s2 s
# 结果 a 2.0 b NaN c 6.0 d NaN dtype: float64 s.isnull()
# 结果 a False b True c False d True dtype: bool
DataFrame
DataFrame是一个【表格型】的数据结构。
DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。
DataFrame既有行索引,也有列索引。
-
行索引:index
-
列索引:columns
-
值:values
DataFrame的创建
-
ndarray创建
-
字典创建
from pandas import DataFrame df = DataFrame(data=[[1,2,3],[4,5,6]]) df
# 结果 0 1 2 0 1 2 3 1 4 5 6 df = DataFrame(data=np.random.randint(0,100,size=(6,4))) df # 结果 0 1 2 3 0 93 61 7 1 1 89 41 29 16 2 21 66 97 24 3 56 96 13 87 4 86 21 20 54 5 19 18 96 7 dic = { 'name':['zhangsan','lisi','wanglaowu'], 'salary':[1000,2000,3000] } df = DataFrame(data=dic,index=['a','b','c']) df # 结果 name salary a zhangsan 1000 b lisi 2000 c wanglaowu 3000
DataFrame的属性
-
values
-
columns
-
index
-
shape
df.values
df.columns
df.index
df.shape
(3, 2)
============================================ 练习4: 根据以下考试成绩表,创建一个DataFrame,命名为df: 张三 李四 语文 150 0 数学 150 0 英语 150 0 理综 300 0 ============================================ dic = { '张三':[150,150,150,150], '李四':[0,0,0,0] } df = DataFrame(data=dic,index=['语文','数学','英语','理综']) df
DataFrame索引操作
-
对行进行索引
-
队列进行索引
-
对元素进行索引
df = DataFrame(data=np.random.randint(60,100,size=(8,4)),columns=['a','b','c','d']) df # 结果 a b c d 0 95 87 83 68 1 76 82 78 95 2 69 94 89 72 3 74 77 93 82 4 75 88 93 64 5 67 98 66 85 6 95 83 71 61 7 72 74 79 82
df['a'] #取单列,如果df有显示的索引,通过索引机制取行或者列的时候只可以使用显示索引
# 结果
0 95 1 76 2 69 3 74 4 75 5 67 6 95 7 72 Name: a, dtype: int64
df[['a','c']] #取多列 # 结果 a c 0 95 83 1 76 78 2 69 89 3 74 93 4 75 93 5 67 66 6 95 71 7 72 79
-
iloc:
-
通过隐式索引取行
-
-
loc:
-
通过显示索引取行
-
#取单行 df.loc[0]
a 95 b 87 c 83 d 68 Name: 0, dtype: int64
#取多行 df.iloc[[0,3,5]] a b c d 0 95 87 83 68 3 74 77 93 82 5 67 98 66 85
#取单个元素 df.iloc[0,2] df.loc[0,'a']
95
#取多个元素 df.iloc[[1,3,5],2]
1 78 3 93 5 66 Name: c, dtype: int64
DataFrame的切片操作
-
对行进行切片
-
对列进行切片
#切行 df[0:2] a b c d 0 95 87 83 68 1 76 82 78 95
#切列 df.iloc[:,0:2] a b 0 95 87 1 76 82 2 69 94 3 74 77 4 75 88 5 67 98 6 95 83 7 72 74
df索引和切片操作
-
索引:
-
df[col]:取列
-
df.loc[index]:取行
-
df.iloc[index,col]:取元素
-
-
切片:
-
df[index1:index3]:切行
-
df.iloc[:,col1:col3]:切列
-
DataFrame的运算
-
同Series
============================================ 练习: 假设ddd是期中考试成绩,ddd2是期末考试成绩,请自由创建ddd2,并将其与ddd相加,求期中期末平均值。 假设张三期中考试数学被发现作弊,要记为0分,如何实现? 李四因为举报张三作弊立功,期中考试所有科目加100分,如何实现? 后来老师发现有一道题出错了,为了安抚学生情绪,给每位学生每个科目都加10分,如何实现? ============================================ dic = { '张三':[150,150,150,150], '李四':[0,0,0,0] } df = DataFrame(data=dic,index=['语文','数学','英语','理综']) qizhong = df qimo = df #期中期末的平均值 (qizhong + qizhong) / 2 张三 李四 语文 150 0 数学 150 0 英语 150 0 理综 150 0
#将张三的数学成绩修改为0 qizhong.loc['数学','张三'] = 0 qizhong 张三 李四 语文 150 0 数学 0 0 英语 150 0 理综 150 0
#将李四的所有成绩+100 qizhong['李四']+=100 qizhong 张三 李四 语文 150 100 数学 0 100 英语 150 100 理综 150 100 #将所有学生的成绩+10 qizhong += 10 qizhong 张三 李四 语文 160 110 数学 10 110 英语 160 110 理综 160 110
时间数据类型的转换
-
pd.to_datetime(col)
将某一列设置为行索引
-
df.set_index()
dic = { 'time':['2010-10-10','2011-11-20','2020-01-10'], 'temp':[33,31,30] } df = DataFrame(data=dic) df time temp 0 2010-10-10 33 1 2011-11-20 31 2 2020-01-10 30
#查看time列的类型 df['time'].dtype dtype('O') import pandas as pd #将time列的数据类型转换成时间序列类型 df['time'] = pd.to_datetime(df['time']) df time temp 0 2010-10-10 33 1 2011-11-20 31 2 2020-01-10 30 df['time'] 0 2010-10-10 1 2011-11-20 2 2020-01-10 Name: time, dtype: datetime64[ns]
#将time列作为源数据的行索引 df.set_index('time',inplace=True) time temp 2010-10-10 33 2011-11-20 31 2020-01-10 30

浙公网安备 33010602011771号