数据分析常用库
numpy:数组计算
NumPy是高性能科学计算和数据分析的基础包。它是pandas等其他各种工具的基础。
NumPy的主要功能(*为不常用)
ndarray,一个多维数组结构,高效且节省空间 无需循环对整组数据进行快速运算的数学函数 *读写磁盘数据的工具以及用于操作内存映射文件的工具 *线性代数、随机数生成和傅里叶变换功能 *用于集成C、C++等代码的工具
简介
1.为什么要使用ndarray: 占用内存小 计算速度快 数学运算方法多 2.ndarray还可以是多维数组,但元素类型必须相同 3.类型转换:astype()
常用属性
T 数组的转置(对高维数组而言) dtype 数组元素的数据类型 size 数组元素的个数 ndim 数组的维数 shape 数组的维度大小(以元组形式) reshape 格式化一个矩阵(一维->多维) ravel 格式化一个矩阵(多维->一维)
创建ndarray
array([]) 将python列表转换为数组,可选择显式指定dtype arange() range的numpy版,支持浮点数 zeros() 根据指定形状和dtype创建全0数组 ones() 根据指定形状和dtype创建全1数组 *linspace() 类似arange(),第三个参数为数组长度 *empty() 根据指定形状和dtype创建空数组(随机值)
索引和切片
数组和标量之间的运算 a+1 a*3 1//a a**0.5 同样大小数组之间的运算 a+b a/b a**b 数组的索引 a[5] a2[2][3] a2[2,3] 数组的切片 a[5:8] a[:3] = 1 a2[1:2, :4] a2[:,:1] a2[:,1] 与列表不同,数组切片时并不会自动复制,在切片数组上的修改会影响原数组。 【解决方法:copy()】 b = a[:4] b[-1] = 250 b = a[:4].copy() b[-1] = 250
布尔型索引
In [8]: import numpy as np In [9]: a Out[9]: array([1, 2, 3] In [10]: b=np.array([True,False,True]) In [11]: a[b] Out[11]: array([1, 3])
In [19]: a<3 Out[19]: array([ True, True, False], dtype=bool) In [20]: a[a<3] Out[20]: array([1, 2]) In [21]: a[(a<3) & (a%2==0)] # 并且& 或| Out[21]: array([2])
花式索引
In [7]: a[[0,2]] Out[7]: array([1, 3])
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) y = x[[0, 1, 2], [0, 1, 0]] print x print y ### [[1 2] [3 4] [5 6]] [1 4 5]
通用函数
通用函数:能同时对数组中所有元素进行运算的函数 常见通用函数: 一元函数:abs, sqrt, ceil, floor, rint, trunc, modf, isnan, isinf, cos, sin, tan,exp, log, 二元函数:maximum, mininum,add, substract, multiply, divide, power, mod
数学和统计方法
常用函数: sum 求和,多维的有axis按行和列求和 mean 求平均数 min 求最小值 max 求最大值 std 求标准差 var 求方差 argmin 求最小值索引 argmax 求最大值索引
随机数生成
rand 给定形状产生随机数组(0到1之间的数) randint 给定形状产生随机整数 choice 给定形状产生随机选择 shuffle 与random.shuffle相同 uniform 给定形状产生随机数组
pandas:数据分析
pandas是一个强大的Python数据分析的工具包。
pandas是基于NumPy构建的。
pandas的主要功能
具备对其功能的数据结构DataFrame、Series 集成时间序列功能 提供丰富的数学运算和操作(得益于基于numpy) 灵活处理缺失数据
Series
简介
Series是一种类似于一维数组的对象,由一组数据和一组与之相关的数据标签(索引)组成。
Series比较像列表(数组)和字典的结合体
获取值数组和索引数组:values属性和index属性
创建方式
可通过列表list、数组np.array、字典dict创建
In [22]: import pandas as pd In [23]: pd.Series([4,7,-5,3]) Out[23]: 0 4 1 7 2 -5 3 3 dtype: int64 In [24]: pd.Series([4,7,-5,3],index=['a','b','c','d']) Out[24]: a 4 b 7 c -5 d 3 dtype: int64 In [25]: pd.Series({'a':1, 'b':2}) Out[25]: a 1 b 2 dtype: int64 In [26]: pd.Series(0, index=['a','b','c','d']) Out[26]: a 0 b 0 c 0 d 0 dtype: int64
Series特性
Series支持NumPy模块的特性(下标): 从ndarray创建Series:Series(arr) 与标量运算:sr*2 两个Series运算:sr1+sr2 索引:sr[0], sr[[1,2,4]] 切片:sr[0:2] 通用函数:np.abs(sr) 布尔值过滤:sr[sr>0] Series支持字典的特性(标签): 从字典创建Series:Series(dic), in运算:’a’ in sr 键索引:sr['a'], sr[['a', 'b', 'd']]
Series特性
Series支持NumPy模块的特性(下标): 从ndarray创建Series:Series(arr) 与标量运算:sr*2 两个Series运算:sr1+sr2 索引:sr[0], sr[[1,2,4]] 切片:sr[0:2] 通用函数:np.abs(sr) 布尔值过滤:sr[sr>0] Series支持字典的特性(标签): 从字典创建Series:Series(dic), in运算:’a’ in sr 键索引:sr['a'], sr[['a', 'b', 'd']]
整数索引
如果索引是整数类型,则根据整数进行数据操作时总是面向标签(字符串)的。iloc可解决
In [14]: pd.Series([4,7,-5,3]) Out[14]: 0 4 1 7 2 -5 3 3 dtype: int64 In [15]: _.iloc[-1] Out[15]: 3
数据对齐
In [7]: import pandas as pd In [8]: sr1 = pd.Series([12,23,34], index=['c','a','d']) ...: sr2 = pd.Series([11,20,10], index=['d','c','a',]) ...: In [9]: sr1 Out[9]: c 12 a 23 d 34 dtype: int64 In [10]: sr2 Out[10]: d 11 c 20 a 10 dtype: int64 In [11]: sr1+sr2 Out[11]: a 33 c 32 d 45 dtype: int64 In [12]: sr1.add(sr2) Out[12]: a 33 c 32 d 45 dtype: int64 In [13]: sr3 = pd.Series([11,20,10,14], index=['d','c','a','b']) ...: sr1+sr3 ...: Out[13]: a 33.0 b NaN c 32.0 d 45.0 dtype: float64 In [14]: sr1.add(sr3) Out[14]: a 33.0 b NaN c 32.0 d 45.0 dtype: float64 In [15]: sr1.add(sr3, fill_value=0) Out[15]: a 33.0 b 14.0 c 32.0 d 45.0 dtype: float64
缺失数据
缺失数据:使用NaN(Not a Number)来表示缺失数据。其值等于np.nan。内置的None值也会被当做NaN处理。 处理缺失数据的相关方法: dropna() 过滤掉值为NaN的行 fillna() 填充缺失数据 isnull() 返回布尔数组,缺失值对应为True notnull() 返回布尔数组,缺失值对应为False 过滤缺失数据:sr.dropna() 或 sr[data.notnull()] 填充缺失数据:fillna(0)
DataFrame
DataFrame是一个表格型的数据结构,含有一组有序的列。
DataFrame可以被看做是由Series(列或行都是Series)组成的字典,并且共用一个索引。
获取某个小DataFrame:loc和iloc
获取某个值:df[str].iloc[int],df.loc[,] , df.iloc[,]
创建方式
pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]}) pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), 'two':pd.Series([1,2,3,4],index=['b','a','c','d'])})
csv文件读取与写入
df = pd.read_csv('filename.csv') df.to_csv()
常用属性及方法
index 获取行索引 T 转置 columns 获取列索引 values 获取值数组 describe() 获取快速统计
索引和切片
DataFrame有行索引和列索引。
由于DataFrame行索引和列索引有诸多不可确定性(切片解释为行索引,字符串解释为列索引),推荐用loc和iloc索引
通过标签获取
df['A'] df[['A', 'B']] df['A'][0] df[0:10][['A', 'C']] df.loc[:,['A','B']] df.loc[:,'A':'C'] df.loc[0,'A'] df.loc[0:10,['A','C']]
通过位置获取:
df.iloc[3] df.iloc[3,3] df.iloc[0:3,4:6] df.iloc[1:5,:] df.iloc[[1,2,4],[0,3]]
选取总结
1.pandas的索引 * 注意df.iloc、df.loc、df[]的区别 1.四种索引形式: 使用位置做索引 使用列表做索引 使用切片做索引 使用bool类型索引 2.df.loc与df.iloc 2.1 选取行 df.loc 是基于索引值的,切片是左闭右闭的 df.iloc 是基于位置的,切片是左闭右开的 2.2 选取行和列 [,] 逗号左边索引行,逗号右边索引行(左值和右值均可为空) df.loc[,] df.iloc[,] 方括号内必须均为数字 如df.loc[0:5,'年龄'] 等同于 df['年龄'].iloc[0:5] 2.3 选取列 df['列名'] df['列名','列名2',...] df.loc[df['年龄']>18] 3.df.loc与df 3.1 语法上: 相同点:选取行时,即df.loc[] 等同于 df[] 不同点:切片是左闭右闭,df切片是左闭右开的 4.总结 df *选取列(主要):df['列名']选取单列,df['列名','列名2',...]选取多列, 选取行:df是df.loc的选取行的一种简单形式 df.loc 功能强大:主要用于便捷选取行和列,如df.loc[0:3,['性别','年龄']],不需要多次[] df.iloc *选取行: 当索引不为0,1,2,3...时,如设置时间为索引,仍然可采用df.iloc[n]的形式
通过布尔值过滤
df[df['A']>0] df[df['A'].isin([1,3,5])] df[df<0]=0
数据对齐与缺失
DataFrame对象在运算时,同样会进行数据对其,结果的行索引与列索引分别为两个操作数的行索引与列索引的并集。
DataFrame处理缺失数据的方法
dropna(axis=0,where='any',…) fillna() isnull() notnull()
matplotlib:绘图
Matplotlib是一个强大的Python绘图和数据可视化的工具包。 安装方法:pip install matplotlib 引用方法:import matplotlib.pyplot as plt 绘图函数:plt.plot() 显示图像:plt.show()
plot函数
plot函数: 线型linestyle(-,-.,--,..) 点型marker(v,^,s,*,H,+,x,D,o,…) 颜色color(b,g,r,y,k,w,…) plot函数绘制多条曲线 标题:set_title x轴:set_xlabel y轴:y_label 其他类型图像: hist 频数直方图
基础绘图函数
案例
import numpy as np import matplotlib.pyplot as plt def f(t): return np.exp(-t) * np.cos(2 * np.pi * t) a = np.arange(0.0, 5.0, 0.2) plt.subplot(211) plt.plot(a, f(a)) plt.subplot(2, 1, 2) plt.plot(a, np.cos(2 * np.pi * a), 'r--') plt.show()
总结
1.numpy 偏向于构建数据结构,pandas偏向于应用数据结构,matplotlib用于图形展示
2.numpy类似数组(元素类型必须相同), pandas提供字典和多维数组(多个字典组成的数组:横向索引为字符串,列索引为数字)
3.pandas的字典(series)基于numpy的ndArray类型和新定义的Index类型构成,pandas的数组(dataFrame)就是多个series即dataFrame的一列为一个series
Scipy
简介
科学计算中的核心包,提供如插值、积分、优化、图像处理等
数据处理过程
数据收集 数据探索与预处理 数据分析与挖掘 结果评价与呈现