数据分析

Jupyter Notebook

Jupyter Notebook是在Ipython基础上改进的一款编辑器
Ipython 
    安装:pip3 install ipython 
     技巧:
        1.%timeit 代码 执行这个代码1000次使用的时间
        2.!windows下的命令

Jupyter Notebook:
    安装方法:
        1.命令行安装
            pip3 install jupyter
            缺点:
                后面所用的数据分析的包(numpy,pandas以及matplotlib),必须自己手动安装(pip3 install numpy),可能需要解决包与包之间的一些依赖
            启动:
                jupyter notebook
        2.anaconda
            启动anaconda:windows+Q 搜索:anaconda 点击启动
            启动Jupyter:点击Launch 创建的文件在C盘下用户中电脑名的文件夹中     

1、numpy

快捷键:
    1.shift+ enter : 运行当前选中的代码块,然后选中下一个单元格
    2.ctrl + enter : 运行当前选中的代码块

    命令模式下 (ESC显示蓝色):
        a : 在当前选中的单元格之上,插入一个新的单元格
        b : 在当前选中的单元格之下,插一个新的单元格
        dd :删除当前单元格

向量操作

import numpy as np
li1 = [1,2,3,4]
li2 = [5,6,7,8]
np1 = np.array(li1)
np2 = np.array(li2)
np1 * np2  #array([ 5, 12, 21, 32])
np1 + np2  #array([ 6,  8, 10, 12])
np1 - np2  #array([-4, -4, -4, -4])
np1 * 5    #array([ 5, 10, 15, 20])

numpy常见的属性:

np1.dtype 数组元素的数据类型
np1.size 数组元素的个数
np1.ndim 数组的维数
np1.shape 数组的维度大小(以元组形式显示)  #(4,)

二维数组 : [[...],[...]]  每个列表中元素个数要相同
np3 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
np3.size  #10
np3.ndim #2
np3.shape #(2,5)  两行五列
np3.T 数组的转置(对高维数组而言)  #变成五行两列的数组

np.array([1,2,3,4,5],dtype = 'float') #声明指定类型 array([1., 2., 3., 4., 5.])
np1.astype('float')  #类型转换 array([1., 2., 3., 4.])

创建ndarray的方式

array() :将列表转化为数组,可选择显示指定dtype
np.array([1,2,3,4,5]) 

arange() :range的numpy版,支持浮点数
np.arange(5)      #array([0, 1, 2, 3, 4])
np.arange(2,5)    #array([2, 3, 4])
np.arange(2,8,2)  #array([2, 4, 6])

linspace() : 类似arange(),第三个参数为数组长度
np.linspace(2,8,num=10) 将2到8之间的数均匀的分为num份

zeros():生成全0的数组
np.zeros(10) 生成10个0组成的数组

ones():生成全1的数组
np.ones(10) 生成10个

reshape()
np1 = np.ones(10)
np1.reshape(2,5) 改成2行5列,行列相乘一定等于原来原来数组元素的个数

索引和切片

一维数据的索引
    np1 = np.arange(1,10)
    np1
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    np1[3]  #4

二维数据的索引
    np2 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
    np2
    array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
    np2[1,2] #8

一维数组的切片
    np1[1:5]
    array([2, 3, 4, 5])

二维数组的切片
    np2[:,2:4] 逗号前面是行,逗号后面是列
    array([[3, 4],
       [8, 9]])

布尔型索引

问题1:给一个数组,选出数组中所有大于5的数。
答案:np1[np1>5]
原理:
    np1>5会对np1中的每一个元素进行判断,返回一个布尔数组
    布尔型索引:将同样大小的布尔数组传进索引,会返回一个由所有True对应位置的元素的数组

问题2:给一个数组,选出数组中所有大于5的偶数。
答案:np1[(np1>5)&(np1 % 2 == 0)]

问题3:给一个数组,选出数组中所有大于5的数和偶数。
答案:np1[(np1>5)|(np1 % 2 == 0)]

花式索引

问题1:对于一个数组,选出其第1,3,4,6,7个元素
答案:np1[[1,3,4,6,7]]

通用函数

通用函数:能同时对数组中所有元素进行运算的函数
一元函数:
#abs 求绝对值
np.abs([-1.2,1.2])
array([1.2, 1.2])

#sqrt 开平方根
np.sqrt([1,9,4])
np.sqrt([1,9,4])

#exp 以e为底的指数

#log 以2或10为底的对数函数

#ceil 向上取整
np.ceil([1.2,2.3,3.5])
array([2., 3., 4.])

#floor 向下取整
np.floor([1.2,2.3,3.5])
array([1., 2., 3.])

#rint 四舍五入
np.rint([1.2,2.3,3.5])
array([1., 2., 4.])

#trunc 截取整数
np.trunc([1.7,0.6,2.3,5.6])
array([1., 0., 2., 5.])

#modf 将整数和小数部分分别以两个数组的形式返回
np.modf([2.1,3.8])
(array([0.1, 0.8]), array([2., 3.]))

#isnan (not a number)
np.nan == np.nan
False
np.isnan(np.nan)
True
np.isnan([1,2,3,np.nan])
array([False, False, False,  True])

#isinf 无穷大
np.inf == np.inf
True
np.isinf(np.inf)
True

二元函数
#maximum 
np.maximum([1,3,5],[2,3,4])
array([2, 3, 5])

#minimum
np.minimum([1,3,5],[2,3,4])
array([1, 3, 4])

数学和统计方法

常用函数:
    sum  求和
    mean 求平均数
    std     求平均差
    var     求方差
    min     求最小值
    max     求最大值
    argmin    求最小值索引
    argmax    求最大值索引
    sort    从小到大排序
    
np1 = np.array([1,2,3,4,5,6,7,8,9])
np.sum(np1) #45
np.mean(np1) #5.0
np.var(np1) #((1-5)**2 + (2-5)**2 + ... +(9-5)**2) / 10 = 6.666666666666667
np.std(np1)  #对方差开根号 2.581988897471611
np.min(np1) #1
np.max(np1) #9
np.argmin(np1) #0
np.argmax(np1) #8

随机数生成

np.random常用函数

rand        给定形状产生随机数组(0到1之间的数)
np.random.rand(10)  #生成一个数组由10个0到1之间的数组成
np.random.rand(10,5) #生成一个10行5列的由0到1之间的数组成的数组

randint        给定形状产生随机整数
np.random.randint(10) #生成1个0到10之间的随机数
np.random.randint(2,4,5) #array([3, 2, 3, 2, 3]) 随机生成5个2到4之间的正整数(包含2不包含4)

choice        给定形状产生随机选择

shuffle        与random.shuffle相同
np1 = np.array([1,2,3,4,5,6,7,8,9])
np.random.shuffle(np1)
np1
array([9, 5, 1, 4, 3, 8, 7, 6, 2])

uniform        给定形状产生随机数组(正态分布)
np.random.uniform(0,1,1000) #产生由0-1之间1000个数组成的数组

2.pandas

pandas是一个强大的python数据分析的工具包
pandas是基于Numpy构建的
pandas的主要功能:
    具备对其功能的数据结构DataFrame、Series
    集成时间序列功能
    提供丰富的数学运算和操作
    灵活处理缺失数据
安装方法:pip install pandas
引用方法:import pandas as pd

pandas:Series

Series是一种类似于一维数组的对象,由一组数据和一组与之相关的数据标签(索引)组成。

1.Series创建方式:
import pandas as pd
①sr1 = pd.Series([1,2,3,4])
sr1
0    1
1    2
2    3
3    4
sr1[1]  # 2

自定义索引,仍然保持了索引原有下标
②sr2 = pd.Series([1,2,3,4],index=['a','b','c','d'])
sr2
a    1
b    2
c    3
d    4
sr2['a'] # 1
sr2[0] # 1

③sr3 = pd.Series({'a':1,'b':2})
sr3
a    1
b    2
sr3[0] # 1
sr3['a'] # 1

④sr4 = pd.Series(0, index=['a','b','c','d'])
sr4
a    0
b    0
c    0
d    0
sr4[0]  # 0
sr4['a'] # 0

获取值数组和索引数组:values属性和index属性
sr1.values
array([1, 2, 3, 4], dtype=int64)

sr1.index
RangeIndex(start=0, stop=4, step=1)

2.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']]
    
3.Series数据对齐
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

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

4.Series缺失数据
缺失数据:使用NaN(Not a Number)来表示缺失数据。其值等于np.nan。内置的None值也会被当做NaN处理。
处理缺失数据的相关方法:
dropna()        过滤掉值为NaN的行
fillna()        填充缺失数据
isnull()        返回布尔数组,缺失值对应为True
notnull()        返回布尔数组,缺失值对应为False

过滤缺失数据:sr.dropna() 或 sr[data.notnull()]
sr = pd.Series([1,2,3,4,np.nan])
sr
0    1.0
1    2.0
2    3.0
3    4.0
4    NaN

sr1.dropna()  #这个操作并没有改变sr1原本的数据
0    1.0
1    2.0
2    3.0
3    4.0

sr1.dropna(inplace=True) #会改变原本sr1的数据

填充缺失数据:fillna(0)
sr1.fillna(0,inplace=True)
sr1
0    1.0
1    2.0
2    3.0
3    4.0
4    0.0

pandas:DataFrame

DataFrame是一个表格型的数据结构,含有一组有序的列。
DataFrame可以被看做是由n个Series拼接组成的,并且共用一个索引。

1.DataFrame创建方式:
df =pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
  one two    
0  1   4 
1  2   3 
2  3   2 
3  4   1
df['one']
0    1
1    2
2    3
3    4
Name: one, dtype: int64

pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), 'two':pd.Series([1,2,3,4],index=['b','a','c','d'])})
  one two
a 1.0  2 
b 2.0  1 
c 3.0  3 
d NaN  4 

2.csv文件读取和写入
直接将爬到的数据存为csv文件,csv文件可以由excel打开,也可以由文本模式打开
读取:
df = pd.read_csv('./baba.csv')
df.head() #显示前五条数据
df.tail() #显示后五条数据
写入:
df.to_csv()

3.DataFrame查看数据常用属性及方法
df.index #获取索引
df.values #获取值数组
df.columns #获取列索引
df.T       #转置
df.describe() #获取快速统计

4.DataFrame索引和切片
DataFrame有行索引和列索引。
通过标签获取:
    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']]

通过位置获取(iloc只能传入索引下边):
    df.iloc[3]
    df.iloc[3,3]
    df.iloc[0:3,4:6]
    df.iloc[1:5,:]
    df.iloc[[1,2,4],[0,3]]

通过布尔值过滤:
    df[df['A']>0]
    df[df['A'].isin([1,3,5])]
    df[df<0] = 0
 
5.DataFrame数据对齐与缺失数据
DataFrame对象在运算时,同样会进行数据对其,结果的行索引与列索引分别为两个操作数的行索引与列索引的并集.
DataFrame处理缺失数据的方法:
    dropna(axis=0,where='any',…)
    fillna()
    isnull()
    notnull()
    
6.pandas:其他常用方法
df =pd.DataFrame({'one':[1,2,3,4],'two':[1,2,3,4]})
  one two    
0  1   1 
1  2   2 
2  3   3 
3  4   4

pandas常用方法(适用Series和DataFrame):
    ①mean(axis=0,skipna=False)           #axis=0 行  axis=1 列
    df.mean(axis=0)
    one    2.5
    two    2.5
    dtype: float64
    
    df.mean(axis=1)
    0    1.0
    1    2.0
    2    3.0
    3    4.0
    dtype: float64
    
    ②sum(axis=1)
    
    ③sort_index(axis, …, ascending)        按行或列索引排序
    ascending=True 按升序排(默认)   ascending=False 按降序排
    
    ④sort_values(by, axis, ascending)    按值排序 by通过什么进行排序
    
    NumPy的通用函数同样适用于pandas

7.从文件读取
读取文件:从文件名、URL、文件对象中加载数据
read_csv    默认分隔符为csv    
read_table    默认分隔符为\t

读取文件函数主要参数:
sep            指定分隔符,可用正则表达式如'\s+'
header=None    指定文件无列名
names        指定列名
index_col    指定某列作为索引
skip_row    指定跳过某些行
na_values    指定某些字符串表示缺失值
parse_dates    指定某些列是否被解析为日期,布尔值或列表

df = pd.read_csv('./baba.csv',header=None,names=['日期','最高价','最低价','开盘价','收盘价','成交量','调整收盘价'])

8.写入到文件
写入到文件:
to_csv
df.to_csv('./test.csv',index=False)
写入文件函数的主要参数:
na_rep            指定缺失值转换的字符串,默认为空字符串
header=False    不保存列名
index=False        不保存行索引
cols            指定输出的列,传入列表

9.groupby的用法
df = pd.read_html('https://baike.baidu.com/item/NBA%E6%80%BB%E5%86%A0%E5%86%9B/2173192?fr=aladdin')
df  #拿到网页上的所有table
df[0] #拿到第一个table
nba_champions = df[0]
nba_champions.columns = nba_champions.iloc[0] #列索引为第一行
nba_champions.drop(0,inplace=True)

#每个队获得总冠军的次数,并按照从大到小排列
nba_champions.groupby('冠军').size().sort_values(ascending=False)
nba_champions['冠军'].value_counts()

#获得冠军时的FMVP
nba_champions.groupby(['冠军','FMVP']).size().sort_values(ascending=False)

3.matplotlib

Matplotlib是一个强大的Python绘图和数据可视化的工具包
安装方法:pip install matplotlib
引用方法:import matplotlib.pyplot as plt
绘图函数:plt.plot()
显示图像:plt.show()  #使用魔术方法 %matplotlib inline 就可以不用写show

图像标注
设置图像标题: plt.title()
设置x轴名称:plt.xlabel()
设置y轴名称:plt.ylabel()
设置X轴范围:plt.xlim()
设置Y轴范围:plt.ylim()
设置X轴刻度:plt.xticks()  #plt.xticks(np.arange(0,len(x),10),rotation=90) 旋转90度,x轴每格为10
设置Y轴刻度:plt.yticks()
设置曲线图例:plt.legend()
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  #必须设置字体,汉字才可以显示 windows
x = [2,4,6,8]
y = [1,6,5,4]
plt.figure(figsize=(10,6)) #指定画布大小
plt.title('标题')   #标题  
plt.xlabel('x轴')    #x轴坐标
plt.ylabel('y轴')    #y轴坐标
plt.plot(x,y,color='r',linestyle='--',marker='o')
plt.show()

plot函数:
线型linestyle(-,-.,--,..)
点型marker(v,^,s,*,H,+,x,D,o,…)
颜色color(b,g,r,y,k,w,…)

折线图:plot

柱状图:Bar
x = ['中国','美国','日本']
y = [30,15,20]
plt.figure(figsize=(10,6))
plt.title('各个国家数据',size=20)
plt.xlabel('国家')
plt.ylabel('数量')
plt.bar(x,y)
plt.show()

将数据显示到柱状图上面
for a,b in zip(data.index,data.values):
    plt.text(a,b+100,b,ha='center')  #a,b+100 数据的位置 ha:数据居中显示

饼图:Pie
pd.cut(np.array([0.2, 1.4, 2.5, 6.2, 9.7, 2.1]).[1,2,3])
将数据切割成1-2 ,2-3 两份

s = np.array(df['时长'])
np.where('8U' == s)  #判断8U是否在s里面 显示索引31644
s = np.delete(s,31644,axis=0) #删除8U那一行
data = pd.cut(s.astype('float'),[0,60,90,130,1000]).value_counts() #将时长分为4个区间 并得到没组的个数
x = data.index
y = data.values
plt.pie(y,labels=x,autopct='%.2f%%',colors='bgry')  #autopct:所占比例,.2%表示保留2位小数并且带% , colors各块的颜色
plt.show()
    
  
上面数据都是伪造的,一般情况下数据源需要通过pandas和numpy分析后再经过plot函数或者bar函数,pie函数将图画出来

searbon也是一个画图工具,是matplotlib加强版

日志分析

可以通过用户访问日志分析出访问最多的用户来自哪个国家地区,也可以分析在哪个时间点访问的用户最多.
用户访问nginx服务器.如果用户访问成功,nginx会在服务器上记录一个日志叫做access_log,访问失败会记录一个错误日志叫error_log
现在的大数据就是通过用户对访问日志进行分析,分析完成以后会给用户画一个像

安装分析用的包:pip3 insatall apache-log-parser
import apache_log_parser
    pache HTTP Server(简称Apache)是Apache软件基金会的一个开放源码的网页服务器,可以在大多数计算机操作系统中运行,由于其多平台和安全性被广泛使用,是最流行的Web服务器端软件之一。它快速、可靠并且可通过简单的API扩展,将Perl/Python等解释器编译到服务器中。
    Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。

 我们使用apache-log-parser进行apache-log分析.log解析前我们需要了解对应的网站的Apache-log配置,我们需要分析网站的log格式.
对应的个字段代表内容如下:
    %V - 根据UserCanonicalName设置的服务器名字
    %h - 远程主机(客户端IP)
    %l - identity of the user determined by identd(not usually used sicne not reliable)
    %u - 由HTTP authentication 决定的 user name
    %t - 服务器完成处理这个请求的时间
    %r - 来自客户端的请求行("GET / HTTP/1.0")
    %>s - 服务器端返回给客户的状态码(200,404等)
    %b - 响应给客户端的响应报文大小(in bytes)
    \"%{Referer}i\" - Referer is the page that linked to this URL 上一个网址
    \"%{User-Agent}i\" - the browser identification string 客户端浏览器
    %T - Apache 请求时间
   
通过分析网站的log格式,得到相应的解析规则
fformat= '%V %h %l %u %t \"%r\" %>s %b  \"%{Referer}i\" \"%{User-Agent}i\" %T'

创建解析器
p = apache_log_parser.make_parser(fformat)

要解析的数据
sample_string= '...'

data = p(sample_string)

 

posted @ 2019-05-27 22:33  Zhuang_Z  阅读(229)  评论(0)    收藏  举报