这部分也使用jupyter notebook写的
一、pandas是什么?
Pandas是另一个用于处理高级数据结构和数据分析的python库,名字来源于"panel data"(面板数据)
特点:
- Dataframe是一种高效快速的数据结构对象,Pandas支持Dataframe格式,从而可以自定义索引;
- 可以将不同格式的数据文件加载到内存中;
- 未对齐及索引方式不同的数据可按轴自动对齐;
- 可处理时间序列或非时间序列数据;
- 可基于标签来切片索引,获得大数据集子集
- 可进行高性能数据分组、聚会、添加、删除
- 灵活处理数据缺失、重组、空格。
二、Pandas数据结构
1.Series
(1)创建Series数组
import pandas as pd
s1 = pd.Series([1,2,3,4,5])
print('s1:{}'.format(s1))
# out
s1:0 1 # 左边为索引(默认生成),右边为值
1 2
2 3
3 4
4 5
dtype: int64 # jupyter会输出类型
(2)创建Series数组并设置index参数
s2 = pd.Series([1,2,3,4,5], index=['第一','第二','第三','第四','第五'])
print('s2:{}'.format(s2))
# out
s2:第一 1
第二 2
第三 3
第四 4
第五 5
dtype: int64
(3)Series的索引和切片
通过Series的values和index属性可获取Series中的索引和数值
查看索引和值
print('s2索引:{}'.format(s2.index)) # index不可以修改
print('s2值:{}'.format(s2.values))
# out
s2索引:Index(['第一', '第二', '第三', '第四', '第五'], dtype='object')
s2值:[1 2 3 4 5]
索引多个数值
s2[['第二','第四','第五']] # 索引一个只用一个中括号
# out
第二 2
第四 4
第五 5
dtype: int64
连续索引
s2['第二':'第五']
# out
第二 2
第三 3
第四 4
第五 5
dtype: int64
注意:Series切片末端元素是包含在内的
(4)字典类型数据创建Series
使用pd.Series函数可以将字段类型转化为Series对象
s_dic = {'First':1, 'Second':2, 'Third':3, 'Fourth':4, 'fifth':5}
s4 = pd.Series(s_dic)
print('s4:{}'.format(s4))
# out
s4:First 1
Second 2
Third 3
Fourth 4
fifth 5
dtype: int64
传入index序列按指定序列排序
- 查看某些元素是否在Series数组中用 in、not in
- 判断是否存在缺失值用isnull、notnull
s5 = pd.Series(s_dic, index = ['First','Second','Third','Fourth','Tenth'])
print('s5:{}'.format(s5))
# out
s5:First 1.0
Second 2.0
Third 3.0
Fourth 4.0
Tenth NaN
dtype: float64
(5)Series的算术运算
不同索引对应的数据会自动对齐
print('s4+s5:{}'.format(s4+s5))
# out
s4+s5:First 2.0
Fourth 8.0
Second 4.0
Tenth NaN
Third 6.0
fifth NaN
dtype: float64
2.DataFrame数据结构
(1)创建
# 通过列表创建
import pandas as pd
a = pd.DataFrame()
data = [1,2,5]
score = [3,4,6] # 保证data和score长度一样
a['data'] = data
a['score'] = score
a
df_dic = {'color':['red','yellow','blue','purple','pink'],
'size':['medium','small','big','medium','small'],
'taste':['sweet','sour','salty','sweet','spicy']}
df = pd.DataFrame(df_dic)
print(df)
# out
color size taste
0 red medium sweet
1 yellow small sour
2 blue big salty
3 purple medium sweet
4 pink small spicy
- 指定列,传入columns函数
df1 = pd.DataFrame(df_dic,columns=['taste','color','size'])
print(df1)
# out
taste color size
0 sweet red medium
1 sour yellow small
2 salty blue big
3 sweet purple medium
4 spicy pink small
- 传入的columns中含有与原字典数据key值不匹配的列名称时,该列会被记作NaN列
df2 = pd.DataFrame(df_dic,columns=['taste','color','size','category'])
print(df2)
# out
taste color size category
0 sweet red medium NaN
1 sour yellow small NaN
2 salty blue big NaN
3 sweet purple medium NaN
4 spicy pink small NaN
- DataFrame的表头可设置列名称的标题和行索引名称的标题,需使用name函数设置
df2.index.name = 'sample'
df2.columns.name = 'feature'
df2
- 使用value函数可以获得DataFrame中的所有数据,以二维数组的形式返回
print('df2的value的值为:{}'.format(df2.values))
# out
df2的value的值为:[['sweet' 'red' 'medium' nan]
['sour' 'yellow' 'small' nan]
['salty' 'blue' 'big' nan]
['sweet' 'purple' 'medium' nan]
['spicy' 'pink' 'small' nan]]
(2)DataFrame的索引
print('df2中的color列:{}'.format(df2['color']))
print('df2中的color列:{}'.format(df2.color))
print('df2中行序号为3:{}'.format(df2.ix[3])) # 行索引
df2.iloc[] # 行索引,里面填行名称或数字 -1代表最后一行
- 通过索引,对特定数组修改
import numpy as np
df2['category'] = np.arange(5)
print('df2:{}'.format(df2))
# out
df2:feature taste color size category
sample
0 sweet red medium 0
1 sour yellow small 1
2 salty blue big 2
3 sweet purple medium 3
4 spicy pink small 4
- 只希望填充部分数值
df2['category'] = pd.Series([2,3,4], index=[0,2,4])
print('df2:{}'.format(df2))
# out
df2:feature taste color size category
sample
0 sweet red medium 2.0
1 sour yellow small NaN
2 salty blue big 3.0
3 sweet purple medium NaN
4 spicy pink small 4.0
- 为不存在的列赋值将会创建一个新的列
df2['country'] = pd.Series(['Chain','UK','USA','Australia','Japan'])
print('df2:{}'.format(df2))
# out
df2:feature taste color size category country
sample
0 sweet red medium 2.0 Chain
1 sour yellow small NaN UK
2 salty blue big 3.0 USA
3 sweet purple medium NaN Australia
4 spicy pink small 4.0 Japan
(3)pandas优化的选择方式
- df.loc # 通过标签索引行数据
- df.iloc # 通过位置获取行数据
三、数学与统计运算
1、先创建一个DataFrame
df = pd.DataFrame([[3,2,3,1],[2,5,3,6],[3,4,5,2],[9,5,3,1]],
index=['a','b','c','d'],columns=['one','two','three','four'])
print('df:{}'.format(df))
# out
df: one two three four
a 3 2 3 1
b 2 5 3 6
c 3 4 5 2
d 9 5 3 1
print('df.sum 按列求和:{}'.format(df.sum()))
print('df.sum 按行求和:{}'.format(df.sum(axis=1)))
# out
df.sum 按列求和:one 17
two 16
three 14
four 10
dtype: int64
df.sum 按行求和:a 9
b 16
c 14
d 18
dtype: int64
2、 常用的DataFrame数据统计函数
统计函数 | 解释 |
---|---|
mean | 均值 |
median | 中位数 |
count | 非缺失值数量 |
min、max | 最大最小值 |
describe | 汇总统计 |
var | 方差 |
std | 标准差 |
skew | 偏度 |
kurt | 精度 |
diff | 一阶差分 |
cumin、cummax | 累计最大值、累计最小值 |
cunsum、cumprod | 累计和、累计积 |
cov、corr | 协方差、相关系数 |
3、整体查看
shape 获取行数和列数
describe 快速查看一些信息
value_counts() 查看某一列有几种数据
四、DataFrame的文件操作
1.读取文件
读取数据文件函数 | 解释 |
---|---|
pd.read_csv(filename) | 从csv文件导入数据,默认分隔符为‘,’ |
pd.read_table(filename) | 从文本文件文件导入数据,默认分隔符为制表符 |
pd.read_excel(filename) | 从Excel中导入数据 |
pd.read_sql(query, connection_object) | 从SQL表、库中导入数据 |
pd.read_json(json_string) | 从json文件中导入数据 |
pd.read_html(url) | 解析URL、字符串或者HTML文件,提取数据表格 |
pd.DataFrame(dict) | 从字典对象中导入数据 |
# sheet_name用于指定要读取的工作表,0为第一个工作表;index_col用于设置某一列为行索引
data=pd.read_excel('a.xlsx', sheet_name=0, encoding='utf-8')
# delimiter指定分隔符号,默认逗号
data=pd.read_csv('a.csv', delimiter=',', encoding='utf-8')
2.写入文件
写入文件函数 | 解释 |
---|---|
df.to_csv(filename) | 导出数据至csv文件 |
df.to_excel(filename) | 导出数据至excel文件 |
df.to_sql(table_name, connection_object) | 导出数据至SQL表 |
df.to_json(filename) | 导出数据为json格式 |
df.to_html(filename) | 导出数据为html文件 |
df.to_clipboard(filename) | 导出数据到剪贴板中 |
五、数据处理
1.缺失值处理
缺失值在数据中的表现主要有三种:
- 不存在型空值,也就是无法获取的值,比如未婚人士的配偶姓名。
- 存在型空值,样本的该特征是存在的,但是暂时无法获取数据,之后该信息一旦被确定,就可以补充数据,是信息趋于完整
- 占位型空值,无法确定是不存在型空值还是存在型空值,需要随着时间的推移来确定
(1)查找缺失值
- 使用isnull函数判断是否存在缺失值,缺失值一般记作:numpy.nan,表示数据空缺
df4 = pd.DataFrame([[3,np.nan,3,1],[2,5,np.nan,6],[3,4,5,np.nan],[5,3,1,3]],
index=['a','b','c','d'],columns=['one','two','three','four'])
print(df4.isnull())
# out
one two three four
a False True False False
b False False True False
c False False False True
d False False False False
- 结合any函数可以对原DataFrame进行切片,提取所有包含缺失值的数据
print(df4[df4.isnull().any(axis=1)])
# out
one two three four
a 3 NaN 3.0 1.0
b 2 5.0 NaN 6.0
c 3 4.0 5.0 NaN
(2)过滤缺失值
- dropna函数用于过滤缺失值,可返回不含有缺失值的数据和索引
- dropna函数返回的是一个执行了删除操作之后的新数组
- 传入参数为inplace=True,会直接在原数据上进行删除操作
- 传入how='all’可以删除全为缺失值NaN的行或列
(3)填充缺失值
- fillna函数,传入替换后的数值
- print(df4.fillna(0)) # 用0替换缺失值
- df4.fillna(df4.median()) # 中位数填补缺失值
- df4.ffill() # 向上填充缺失值
- df4.bfill() # 向下填充缺失值
2.重复值处理
- duplicated函数查看是否存在缺失值
df4 = pd.DataFrame([[3,5,3,1],[2,5,5,6],[3,4,3,5],[5,3,1,3],[3,4,3,5],[3,4,6,8]],
index=['a','b','c','d','e','f'],columns=['one','two','three','four'])
df4
df4[df4.duplicated()]
`df4[df4.duplicated(subset=['one','two'])] #subset用于识别重复的列标签或行标签`
- 去除重复值
df4.drop_duplicates(subset=['one','two'],keep='first')
# keep有三个取值first(保留第一次出现的重复值) last False
3.数据记录合并与分组
(1)使用append函数合并
对于两个列索引完全相同的DataFrame,可以使用append函数对二者进行上下合并
df5 = pd.DataFrame([[3,3,2,4],[5,4,3,2]],
index=['g','h'],columns=['one','two','three','four'])
print(df4.append(df5))
# out
one two three four
a 3 5 3 1
b 2 5 5 6
c 3 4 3 5
d 5 3 1 3
e 3 4 3 5
f 3 4 6 8
g 3 3 2 4
h 5 4 3 2
(2)使用concat函数合并
可以指定两个DataFrame按某个轴进行连接,axis=0表示列对其(默认),axis=1表示行对齐,两表左右结合
print(pd.concat([df4, df5])) #和append效果相同
print(pd.concat([df4, df5], axis=1)) # 左右连接
# out
one two three four
a 3 5 3 1
b 2 5 5 6
c 3 4 3 5
d 5 3 1 3
e 3 4 3 5
f 3 4 6 8
g 3 3 2 4
h 5 4 3 2
one two three four one two three four
a 3.0 5.0 3.0 1.0 NaN NaN NaN NaN
b 2.0 5.0 5.0 6.0 NaN NaN NaN NaN
c 3.0 4.0 3.0 5.0 NaN NaN NaN NaN
d 5.0 3.0 1.0 3.0 NaN NaN NaN NaN
e 3.0 4.0 3.0 5.0 NaN NaN NaN NaN
f 3.0 4.0 6.0 8.0 NaN NaN NaN NaN
g NaN NaN NaN NaN 3.0 3.0 2.0 4.0
h NaN NaN NaN NaN 5.0 4.0 3.0 2.0
- join参数用来设置连接方式,默认为outer(取并集)
- join='inner’表示取交集,只返回两数据集都匹配成功的数据
(3)使用merge函数合并
根据两个DataFrame共有的某个字段进行数据合并(相当于数据库的连接查询)
# 创建俩个数据集
df_dic = {'color':['red','yellow','blue','purple','pink'],
'size':['medium','small','big','medium','small'],
'taste':['sweet','sour','salty','sweet','spicy'],
'category':[2,3,4,5,6]}
df6 = pd.DataFrame(df_dic, columns=['taste','color','size','category'])
print('df6:{}'.format(df6))
df_dic1 = {'country':['China','UK','USA','Australia','Japan'],
'quality':['good','normal','excellent','good','bad'],
'category':[2,3,5,6,7]}
df7 = pd.DataFrame(df_dic1,columns=['country','quality','category'])
print('df7:{}'.format(df7))
# out
df6: taste color size category
0 sweet red medium 2
1 sour yellow small 3
2 salty blue big 4
3 sweet purple medium 5
4 spicy pink small 6
df7: country quality category
0 China good 2
1 UK normal 3
2 USA excellent 5
3 Australia good 6
4 Japan bad 7
# 输出合并之后的数据集
print(pd.merge(df6,df7,left_on='category',right_on='category',how='left'))
# out
taste color size category country quality
0 sweet red medium 2 China good
1 sour yellow small 3 UK normal
2 salty blue big 4 NaN NaN
3 sweet purple medium 5 USA excellent
4 spicy pink small 6 Australia good
- left_on参数表示主键在左侧DataFrame中的列名称,right_on参数表示主键在右侧DataFrame中的列名称,两者名称可以不同
- how参数的值可以为‘left’、‘right’、‘outer’
(4)排序
sort_values(by="c1", ascending=False)
# 按列排序 by指定按哪一列排,ascending为True表示升序
sort_index() # 行根据索引排序
总结
DataFrame的基础属性
- df.shape # 行数 列数
- df.dtypes # 列数据类型
- df.ndim # 数据维度
- df.index # 行索引
- df.columns # 列索引
- df.values # 对象值
DataFrame整体情况查询
- df.head(3) # 显示头部几行,默认5行
- df.tail(3) # 显示末尾几行,默认5行
- df.info() # 相关信息概览
- df.describe() # 快速综合统计结果
学习笔记
《Python3快速入门与实战》