关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

云南大王-初识人工智能(一):数据分析(三):numpy科学计算基础库(二)

发布时间:2020-04-13 00:00:00
1. numpy科学计算基础库 1.1 numpy读取数据 CSV:Comma-Separated Value,逗号分隔值文件显示:表格状态源文件:换行和逗号分隔行列的格式化文本,每一行的数据表示一条记录。 由于csv便于展示,读取和写入,所以很多地方也是用csv的格式存储和传输中小型的数据,为了方便教学,我们会经常操作csv格式的文件,但是操作数据库中的数据也是很容易的实现的。 np.loadtxt(fname,dtype=np.float,delimiter=None,skiprows=0,usecols=None,unpack=False) np.loadtxt(US_video_data_ numbers_path,delimiter=\",\",dtype=int,unpack=1) 注意其中添加delimiter和dtype以及unpack的效果delimiter:指定边界符号是什么,不指定会导致每行数据为一个整体的字符串而报错dtype:默认情况下对于较大的数据会将其变为科学计数的方式那么unpack的效果呢?upack:默认是Flase(0),默认情况下,有多少条数据,就会有多少行为True(1)的情况下,每一列的数据会组成一行,原始数据有多少列,加载出来的数据就会有多少行,相当于转置的效果 1.2 numpy中的转置 转置是一种变换,对于numpy中的数组来说,就是在对角线方向交换数据,目的也是为了更方便的去处理数据。 # coding=utf-8 import numpy as np t = np.array([[0,1,2,3,4,5],[6,7,8,9,10,11],[12,13,1,15,16,17]]) print(t) print(t.swapaxes(1,0)) print(t.transpose()) print(t.T) 运行结果: 1.3 numpy索引和切片 对于刚刚加载出来的数据,我如果只想选择其中的某一列(行)我们应该怎么做呢? # coding=utf-8 import numpy as np a = np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]]) #取一行 print(a[1]) #取多行 print(a[1:3]) #取一列 print(a[:,2]) #取多列 print(a[:,2:4]) 运行结果: 1.4 numpy中数值的修改 # coding=utf-8 import numpy as np t = np.array([[0,1,2,3,4,5],[6,7,8,9,10,11],[12,13,14,15,16,17],[18,19,20,21,22,23]]) print(t) print(t[:,2:4]) t[:,2:4] = 0 print(t) 运行结果: 1.5 numpy中布尔索引 # coding=utf-8 import numpy as np t = np.arange(24).reshape((4,6)) print(t) print(t<10) t[t<10] = 0 print(t) 运行结果: 1.6 numpy中三元运算符 # coding=utf-8 import numpy as np t = np.arange(24).reshape((4,6)) print(t) print(np.where(t<10,0,10)) 运行结果: 1.7 numpy中的nan和inf nan(NAN,Nan):not a number表示不是一个数字 什么时候numpy中会出现nan: 当我们读取本地的文件为float的时候,如果有缺失,就会出现nan 当做了一个不合适的计算的时候(比如无穷大(inf)减去无穷大) inf(-inf,inf):infinity,inf表示正无穷,-inf表示负无穷 什么时候回出现inf包括(-inf,+inf) 比如一个数字除以0,(python中直接会报错,numpy中是一个inf或者-inf) # coding=utf-8 import numpy as np #两个nan是不相等的 print(np.nan == np.nan) print(np.nan != np.nan) #以上的特性,判断数组中nan的个数 t = np.array([1.,2.,np.nan]) print(np.count_nonzero(t!=t)) #由于np.nan != np.nan为True,那么如何判断一个数字是否为nan呢? #通过np.isnan(a)来判断,返回bool类型,比如希望把nan替换为0 t[np.isnan(t)]=0 print(t) #nan和任何值计算都为nan 运行结果: # coding=utf-8 import numpy as np def fill_ndarray(t1): for i in range(t1.shape[1]): # 遍历每一列 temp_col = t1[:, i] # 当前的一列 nan_num = np.count_nonzero(temp_col != temp_col) if nan_num != 0: # 不为0,说明当前这一列中有nan temp_not_nan_col = temp_col[temp_col == temp_col] # 当前一列不为nan的array # 选中当前为nan的位置,把值赋值为不为nan的均值 temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean() return t1 if __name__ == '__main__': t1 = np.arange(24).reshape((4, 6)).astype("float") t1[1, 2:] = np.nan print(t1) t1 = fill_ndarray(t1) print(t1) 运行结果: 1.8 numpy中常用统计函数 求和:t.sum(axis=None)均值:t.mean(a,axis=None) 受离群点的影响较大中值:np.median(t,axis=None) 最大值:t.max(axis=None) 最小值:t.min(axis=None)极值:np.ptp(t,axis=None) 即最大值和最小值只差标准差:t.std(axis=None) 标准差是一组数据平均值分散程度的一种度量。一个较大的标准差,代表大部分数值和其平均值之间差异较大;一个较小的标准差,代表这些数值较接近平均值反映出数据的波动稳定情况,越大表示波动越大,约不稳定。 缺失值填充均值: # coding=utf-8 import numpy as np def fill_ndarray(t1): for i in range(t1.shape[1]): #遍历每一列 temp_col = t1[:,i] #当前的一列 nan_num = np.count_nonzero(temp_col!=temp_col) if nan_num !=0: #不为0,说明当前这一列中有nan temp_not_nan_col = temp_col[temp_col==temp_col] #当前一列不为nan的array # 选中当前为nan的位置,把值赋值为不为nan的均值 temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean() return t1 if __name__ == '__main__': t1 = np.arange(24).reshape((4, 6)).astype("float") t1[1, 2:] = np.nan print(t1) t1 = fill_ndarray(t1) print(t1) 运行结果: 1.9 numpy生成随机数 1.10 实例运用 假设我们现在有一个英国和美国各自youtube1000多个视频的点击,喜欢,不喜欢,评论数量(["views","likes","dislikes","comment_total"])的csv,运用刚刚所学习的只是,我们尝试来对其进行操作。 准备数据:youtube_video_data.rar 案例1: import numpy as np from matplotlib import pyplot as plt us_file_path = "./US_video_data_numbers.csv" uk_file_path = "./GB_video_data_numbers.csv" # t1 = np.loadtxt(us_file_path,delimiter=",",dtype="int",unpack=True) t_us = np.loadtxt(us_file_path,delimiter=",",dtype="int") #取评论的数据 t_us_comments = t_us[:,-1] #选择比5000小的数据 t_us_comments = t_us_comments[t_us_comments<=5000] print(t_us_comments.max(),t_us_comments.min()) d = 50 bin_nums = (t_us_comments.max()-t_us_comments.min())//d #绘图 plt.figure(figsize=(20,8),dpi=80) plt.hist(t_us_comments,bin_nums) plt.show() 运行结果: 案例2: import numpy as np from matplotlib import pyplot as plt us_file_path = "./US_video_data_numbers.csv" uk_file_path = "./GB_video_data_numbers.csv" # t1 = np.loadtxt(us_file_path,delimiter=",",dtype="int",unpack=True) t_uk = np.loadtxt(uk_file_path,delimiter=",",dtype="int") #选择喜欢书比50万小的数据 t_uk = t_uk[t_uk[:,1]<=500000] t_uk_comment = t_uk[:,-1] t_uk_like = t_uk[:,1] plt.figure(figsize=(20,8),dpi=80) plt.scatter(t_uk_like,t_uk_comment) plt.show() 运行结果:

/template/Home/Zkeys/PC/Static