文章目录

  • 一、Numpy
    • 1.1 Numpy的属性
    • 1.2 Numpy的矩阵创建
    • 1.3 矩阵的运算
    • 1.4 Numpy的随机数操作
    • 1.5 Numpy矩阵索引
    • 1.6 Numpy矩阵的分割
  • 二、Matplotlib
    • 2.1 Matplotlib基本绘制
    • 3.2 调整图像的参数
    • 3.3 绘制其他图像
  • 三、Pandas
    • 3.1 Pandas中的数据结构
    • 3.2 Pandas中的数据选择
    • 3.3 Pandas的数据赋值
    • 3.4 Pandas的错误数据处理
    • 3.5 Pandas的数据合并

一、Numpy

1.1 Numpy的属性

import numpy as nparray = np.array([[1, 2, 3], [4, 5, 6]])  # 定义一个矩阵print(array)
print('array的类型:', type(array))  # np中的矩阵类型:numpy.ndarray
print('array的维度:', array.ndim)
print('array的形状:', array.shape)
print('array中的元素个数:', array.size)
print('array中的元素类型:', array.dtype)

1.2 Numpy的矩阵创建

import numpy as npa1 = np.array([1, 2, 3])  # []的嵌套数量表示矩阵的维数
print("一维矩阵=>", a1)a2 = np.array([[1, 2, 3], [4, 5, 6]])
print("二维矩阵=>", a2)a3 = np.zeros((2, 3))  # 2行3列的矩阵
print("零(2 * 3)矩阵=>", a3)a4 = np.array([1, 2, 3], dtype=float)  # 可以指定元素的类型
print("指定类型后的矩阵=>", a4.dtype)a5 = np.arange(5)  # 定义一个[1:n) 长度的矩阵,步长为1
print("=>", a5)a6 = np.arange(2, 20, 3)  # 区间[2, 20), 步长为3
print("=>", a6)a7 = np.arange(6).reshape(2, 3)  # 重新指定矩阵的形状,元素个数前后必须相等
print("=>", a7)

1.3 矩阵的运算

import numpy as nparr1 = np.array([[1, 2, 3], [2, 3, 5]])
arr2 = np.array([[2, 4, 3], [1, 5, 5]])# 运算的两个矩阵的形状需要相同
print(arr1 + arr2) # 矩阵加法
print(arr1 - arr2) # 矩阵减法
print(arr1 / arr2) # 矩阵除法
print(arr1 % arr2) # 矩阵取模
print(arr1 // arr2) # 矩阵取整
print(arr1 * arr2) # 矩阵的点积运算,对应位置数值相乘
print(arr1 ** arr2) # 矩阵幂运算,arr2作为arr1的幂arr3 = np.ones((3, 6))
print(arr3)# 形状不同的两个矩阵之间进行矩阵乘法
print(np.dot(arr1, arr3))
# 或
print(arr1.dot(arr3))print(arr1.T) # 转置矩阵
# 或
print(np.transpose(arr1))print(arr1 + 2) # 矩阵对应位置元素加上某一个数值print(arr1 > 3) # 判断矩阵中每个位置元素是否大于3
"""
[[False False False][False False  True]]
"""

1.4 Numpy的随机数操作

import numpy as nparr1 = np.random.random((2, 3))  # 生成2行3列,范围(0, 1)之间的随机数矩阵
print(arr1)arr2 = np.random.normal(size=(2, 3))  # 生成2行3列, 符合标准正态分布的随机数矩阵
print(arr2)arr3 = np.random.randint(0, 10, size=(2, 3))  # 在[0, 10]范围上生成2行3列的矩阵,元素均为Int类型
print(arr3)print("元素最大值索引下标", arr1.argmax())
print("元素最小值索引下标", arr1.argmin())print("元素最大值=>", np.max(arr1))
print("元素最小值=>", np.min(arr1))"""
axis为0,按列计算;axis为1,按行计算
axis为元组时,可以指定求和的维度
"""
print("矩阵求和=>", np.sum(arr1))
print("按列进行求和=>", np.sum(arr1, axis=1))
arr4 = np.random.random((2, 3, 2))
# print(arr3)
print(np.sum(arr4, axis=(0, 1, 2)))  # 对指定的0,1,2维度进行求和print("对矩阵求均值=>", np.mean(arr1))  # 求矩阵的均值
print(np.sqrt(arr3))  # 对矩阵中的值开方

1.5 Numpy矩阵索引

import numpy as nparr = np.arange(12)
print(arr)# 对于矩阵的操作和切片操作类似
print("矩阵中的第一个元素=>", arr[0])
print("矩阵中的前4个元素=>", arr[:4])
print("矩阵中的最后两个元素=>", arr[-2:])# 更改矩阵的形状
arr = arr.reshape(2, 2, 3)
print(arr)print("修改后矩阵的第一行元素=>", arr[0])  # 此时每一行表示一个元素
print("修改后矩阵的单个元素=>", arr[1][1])
# 或
print("修改后矩阵的单个元素=>", arr[1, 1])for row in arr:  # 迭代的时候按行进行遍历print(row)

1.6 Numpy矩阵的分割

import numpy as nparr = np.arange(12).reshape(4, 3)
print(arr)a1, a2, a3 = np.split(arr, 3, axis=1)  # 水平方向划分为等大的三个矩阵
print("split水平切分=>", a1, a2, a3)
# 或
a1, a2, a3 = np.hsplit(arr, 3)
print("hsplit水平切分=>", a1, a2, a3)a4, a5 = np.split(arr, 2, axis=0)
print("split垂直切分=>", a4, a5)
# 或
a4, a5 = np.vsplit(arr, 2)
print("hsplit水平切分=>", a4, a5)a6, a7, a8 = np.array_split(arr, 3, axis=0)  # 垂直方向不均匀分割
print("array_split垂直不均匀分割=>", a6, a7, a8)

二、Matplotlib

2.1 Matplotlib基本绘制

from tkinter.ttk import Style
from turtle import color
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1, 1, 1000)  # 在[-1, 1]范围上均匀生成1000个数
y1 = 2 * x + 1
y2 = x ** 2plt.figure()  # 每一个figure可以单独创建一个图像; 若不创建图像绘制到同一个图像中
plt.plot(x, y1)  # 绘制图像信息# plt.figure()
plt.plot(x, y2, linestyle='--')  # linestyle可以指定绘制的样式 --表示虚线# 设置横纵坐标的题头
plt.xlabel("I am X")
plt.ylabel("I am Y")# 指定横纵坐标的数字
xticks = np.linspace(-2, 2, 11)
plt.xticks(xticks)
plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])plt.show() # 图像显示

3.2 调整图像的参数

import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1, 1, 1000)
y1 = 2 * x + 1
y2 = x ** 2plt.plot(x, y1)
plt.plot(x, y2, linestyle='--')
plt.xlabel("I am X")
plt.ylabel("I am Y")# 指定横纵坐标的数字
plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])ax = plt.gca()  # 获取坐标轴信息
# ax.spines获取边框信息,设置右边和上为无色
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')# 设置坐标轴经过的原点位置
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))plt.show() # 图像显示

  • 设置图例
l1, = plt.plot(x, y1)  # 绘制图像信息
l2, = plt.plot(x, y2, linestyle='--')  # linestyle可以指定绘制的样式 --表示虚线
# 设置图例
"""
Call signatures::legend()legend(handles, labels)legend(handles=handles)legend(labels)
"""
plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best')

plt.plot返回的是元组类型(handles, labels),由于上述中的l1, l2是handles,第二个位置需要,占位

3.3 绘制其他图像

  • 散点图
import matplotlib.pyplot as plt
import numpy as np# 绘制散点图
x = np.random.normal(0, 1, 500)
y = np.random.normal(0, 1, 500)plt.xlim((-2, 2))  # 显示图像x的范围
plt.xticks(())
plt.yticks(())
# s表示点的大小,c表示颜色,alpha表示点的透明度
plt.scatter(x, y, s=50, c='r', alpha=0.5)
plt.show()

  • 3D图
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3Dflg = plt.figure()
ax = Axes3D(flg)x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X,Y = np.meshgrid(x, y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()

  • 子图
import matplotlib.pyplot as plt
import numpy as npplt.subplot(2, 1, 1)  # 设置第一个图像在2行一列的空间中占据第一个位置
plt.plot([0, 1], [0, 1])"""
设置图像在2行3列的空间中占据第4个位置,因为当前图像需要在第二行
,在当前逻辑下第一行的图像已经占据了等大的三个图像空间
"""
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 1])plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 1])plt.subplot(2, 3, 6)
plt.plot([0, 1], [0, 1])plt.show()

三、Pandas

3.1 Pandas中的数据结构

import pandas as pd
import numpy as nps1 = pd.Series([1, 2, 3, 4, 5])  # 构造Series,表示一维向量
print(s1)s2 = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])  # 指定索引下标
print(s2)print("通过索引访问元素=>", s1[0], s2['e'])# 可以将构造的序列理解成一个顺序不可变的字典
dict_series = {'name': 'zs', 'age': 18}
s3 = pd.Series(dict_series)
print(s3)# 类似的,创建pandas中的另一个数据结构DataFrame
dict_data_frame = {'name': ['zs', 'ls', 'ww', 'dd'],'age': [19, 18, 19, 17]
}
s4 = pd.DataFrame(dict_data_frame)
print(s4)print("打印DataFrame的索引列 ", s4.columns)
print("打印索引信息 ", s4.index)  # RangeIndex(start=0, stop=4, step=1)
print("打印转置矩阵=> \n", s4.T)s4 = s4.sort_values(by='name')  # 按by后的索引信息进行排序
print(s4)
s4 = s4.sort_index(axis=1)  # 按列索引排序
print(s4)
s4 = s4.sort_index(axis=0)  # 按行索引排序
print(s4)

3.2 Pandas中的数据选择

import pandas as pd
import numpy as npdate_label = pd.date_range('20221011', periods=6)  # 创建一个从2022-10-11开始的日期标签
df1 = pd.DataFrame(np.arange(24).reshape(6, 4), index=date_label, columns=['A', 'B', 'C', 'D'])
print(df1)print(df1['A'])  # DataFrame中的每一列都表示为一个Series,可以通过索引的方式进行获取
# 或
print(df1.B)print(df1[0:2]) # 获取前两行end = '\n'
# 通过loc属性获取数据
# 格式: [[行信息], [列信息]]
print(df1.loc[['20221013', '20221015']], end)  # 指定标签获取行信息
print(df1.loc[:, ['A', 'B']], end)  # 通过索引选择指定的列, : 表示选择所有的行
print(df1.loc['20221011', ['A', 'C']], end)# 通过位置信息进行获取(第几行第几列的形式)
print(df1.iloc[2], end)  # 选取第三行
print(df1.iloc[:, 1:3] , end)  # 选择 [1, 3) 列
print(df1.iloc[1:3, 2:4], end) # 选择行[1,3), 列[2, 4)print(df1[df1.A > 6])  # 选择满足要求的某一列数据

3.3 Pandas的数据赋值

import numpy as np
import pandas as pdend = '\n'
columns_name = ['A', 'B', 'C', 'D']data_label = pd.date_range('20221011', periods=6)
df1 = pd.DataFrame(np.arange(24).reshape(6, 4), index=data_label, columns=columns_name)
print(df1, end)df1.iloc[2, 2] = 100  # 将第二行第二列修改为100
print(df1, end)df1.loc['20221012', 'B'] = 200  # 通过标签进行属性的修改
print(df1, end)df1['E'] = 10  # 添加新列,值均为10
print(df1, end)# 添加新列,值随机
# 需要指定index, 否则默认采用0, 1 ...的下标
df1['F'] = pd.Series(np.arange(6) * np.random.randint(0, 10), dtype=int, index=data_label)
print(df1, end)cur_df_row_len = df1.iloc[0].size
new_row = pd.Series(np.arange(cur_df_row_len) * np.random.randint(0, 10), index=df1.columns, name='new row')  # 创建一个新的Series
df1 = df1.append(new_row)  # 为df1中添加新行
print(df1, end)# 指定位置在df中插入一列; 无返回值
df1.insert(1, 'G', df1['D'])
print(df1, end)# 首先使用pop将'G'列弹出,然后插入到df的末尾
store = df1.pop('G')
df1.insert(df1.iloc[0].size, 'G', store)
print(df1, end)# 删除最后一列
del df1['G']
print(df1, end)df2 = df1.drop(['A', 'B'], axis=1)  # 删除AB列
print(df2, end)df3 = df1.drop(['new row'], axis=0)  # 删除指定标签行
print(df3, end)

3.4 Pandas的错误数据处理

import numpy as np
import pandas as pddef generate_number(len, low=0, height=10):return [int(np.random.randint(low, height)) for _ in range(len)]labels = np.arange(20221011, 20221017)
end = '\n'
df1 = pd.DataFrame(np.arange(24).reshape(6, 4), index=labels, columns=['A', 'B', 'C', 'D'])
print(df1)# 创建错误数据
df2 = pd.DataFrame(df1, index=labels, columns=['A', 'B', 'C', 'D', 'E', 'F'])
print(df2, end)
err_E = pd.Series(generate_number(labels[:-1].size), index=labels[:-1], dtype=int)
err_F = pd.Series(generate_number(labels[1:].size), index=labels[1:], dtype=int)
df2['E'] = err_E
df2['F'] = err_F
"""
构造的样例:A   B   C   D    E    F
20221011   0   1   2   3  4.0  NaN
20221012   4   5   6   7  3.0  8.0
20221013   8   9  10  11  8.0  7.0
20221014  12  13  14  15  5.0  4.0
20221015  16  17  18  19  1.0  4.0
20221016  20  21  22  23  NaN  0.0
"""
print(df2, end)"""
删除一行中含有NaN(空值的元素)
axis: 0表示行,1表示列
how: any表示指定方向含有NaN即可, all表示指定方向所有元素都为NaN
"""
df3 = df2.dropna(axis=0, how='any')  # 按要求进行行删除
print(df3, end)
df4 = df2.dropna(axis=1, how='any')  # 按要求进行列删除
print(df4, end)df5 = df2.fillna(value=0)  # 将空值赋值为0
print(df5, end)print(np.any(pd.isnull(df2)))  # 判断是否存在空值(可指定方向),如果有返回False
print(np.all(pd.isnull(df2)))  # 判断是否全部元素为空值(可指定方向),如果是返回True

3.5 Pandas的数据合并

import pandas as pd
import numpy as npend = '\n'
df1 = pd.DataFrame(np.arange(12).reshape(3, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.arange(12, 24).reshape(3, 4), columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.arange(24, 36).reshape(3, 4), columns=['a', 'b', 'c', 'd'])
print(df1)
print(df2)
print(df3, end)# 合并
# df_new = pd.concat((df1, df2, df3), axis=0)
df_new = pd.concat((df1, df2, df3), axis=0, ignore_index=True)  # 忽略原来数据的索引信息
print(df_new, end)df4 = pd.DataFrame(np.arange(24, 36).reshape(3, 4), columns=['a', 'c', 'd', 'e'])
# 当标签不同的两个df进行合并时
df_new_diff = pd.concat((df1, df4), ignore_index=True, axis=0, join='outer')  # join的值: outer / inner
print(df_new_diff, end)
"""
eg:a    b   c   d     e
0   0  1.0   2   3   NaN
1   4  5.0   6   7   NaN
2   8  9.0  10  11   NaN
3  24  NaN  25  26  27.0
4  28  NaN  29  30  31.0
5  32  NaN  33  34  35.0
对于标签不存在的部分使用NaN进行代替当为inner的时候,仅保留相同标签的部分a   c   d
0   0   2   3
1   4   6   7
2   8  10  11
3  24  25  26
4  28  29  30
5  32  33  34
"""

机器学习Python相关套件(np, plt, pd)相关推荐

  1. 【第2期免费送书】 10本机器学习与Python相关书籍等你来领!经典之作,绝对领你心动......

    微信公众号 关键字全网搜索最新排名 [机器学习算法]:排名第一 [机器学习]:排名第一 [Python]:排名第三 [算法]:排名第四 AI系列公开课,限时免费 [强烈推荐] AI 系列免费公开课.. ...

  2. 上手机器学习前,先来学习下Python相关的环境配置吧~

    点击上方"AI派",选择"设为星标" 最新分享,第一时间送达! 作者:奔雷手,目前是名在校学生,当前主要在学习机器学习,也在做机器学习方面的助教,相对还是比较了 ...

  3. 机器学习的相关代码汇总

    机器学习的相关代码汇总 文章目录 机器学习的相关代码汇总 机器学习相关代码汇总 XGBoost 示例1 示例2 SVM 示例1 示例二 EM 示例1 示例二:GMM 贝叶斯网络 示例一 LDA 机器学 ...

  4. 爬取实习吧与python相关的招聘信息及分析与数据可视化

    大数据时代,计算机行业蓬勃发展,越来越多的人投身计算机事业养家糊口.所以该如何选择工作,现在社会需要怎么样的计算机人才,我们该如何对应的提升自己的本领都是尤为重要的.这篇文章就是对实习吧招聘网站有关p ...

  5. python中plot的plt.text_用Python进行数据可视化的第一步,全面详解matplotlib中样式属性...

    上篇内容我们详细了解了Python使用matplotlib绘制一个复杂的正弦函数的方法(参见),上篇内容我们提到了一个属性'b-',简单介绍了它是用来设置线条颜色和样式的属性.今天,我们详细了解一下P ...

  6. 机器学习--python代码实现基于Fisher的线性判别(鸢尾花数据集的分类)

    一.线性分类–判断该函数属于哪一类 先上例题,然后我会通过两种方法来判断该函数属于哪一类 1.图解法 定义 对于多类问题:模式有 ω1 ,ω2 , - , ωm 个类别,可分三种情况: 第一种情况:每 ...

  7. 绘制渐变色扇形图 -基于python - matplotlib 颜色地图plt.cm模块儿

    绘制渐变色扇形图 -基于python - matplotlib 颜色地图cm模块儿         ʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔ ...

  8. Python相关及开发运维资料汇总

    开发相关 FLASK专区 awesome-flask https://github.com/humiaozuzu/awesome-flask 环境管理 p:非常简单的交互式 python 版本管理工具 ...

  9. 几行代码搞定ML模型,低代码机器学习Python库正式开源

    公众号关注 "视学算法" 设为 "星标",消息即可送达! 机器之心报道 机器之心编辑部 PyCaret 库支持在「低代码」环境中训练和部署有监督以及无监督的机器 ...

最新文章

  1. 新的一年你该如何起飞
  2. 函数调用,统计数中'2’的个数
  3. python with循环_Python for循环、while循环
  4. Java集合转化为数组
  5. QNX多线程同步之Barrier(屏障)
  6. HTTP(1)---HTTP 工作原理
  7. Android中MediaRecorder.stop()报错 java.lang.RuntimeException: stop failed.
  8. matlab nc转tif_旬和月NDVI最大值合成MATLAB
  9. django新闻页面编写
  10. linux键盘输入空格失效,电脑键盘空格键失灵不能用如何修复
  11. 回波损耗、反射系数、电压驻波比以及S参数的物理意义
  12. 2.6 如何在新建虚拟机安装搜狗输入法
  13. 关于web站点的欢迎界面
  14. 使用树莓派来做打印服务器
  15. 如何给 SAP UI5 SmartField 添加 Value Help 功能试读版
  16. 银行卡收单业务____单边账___现实生活中单边账的处理
  17. 高考数学有得用计算机吗,高中数学为什么不让用计算器?
  18. centos7.5换源
  19. js获取当前时间写入HTML,html获取当前时间 js获取当前日期的前后4天
  20. 无线网络技术导论笔记(第三讲)

热门文章

  1. 小博老师解析Java核心技术 ——JDBC参数化查询(一)
  2. 通过LR给随手拍的静物照片进行小清新色调的调色
  3. typescript知识点
  4. 语义分割评估指标MIOU
  5. OD调试常见断点及原理(浓缩版)
  6. JavaScript的String的replace和replaceAll的差别
  7. thinkpad重装系统不引导_联想Y400电脑装WIN7无法重装系统的解决方法
  8. jmeter计算测试QPS
  9. ffmpeg实现视频实时动态时间水印
  10. 2020中国云计算公司排名 哪家的云服务器最好用?