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


一、Numpy

1.1 Numpy的属性

import numpy as np

array = 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 np

a1 = 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 np

arr1 = 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 np

arr1 = 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 np

arr = 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 np

arr = 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 np

x = np.linspace(-1, 1, 1000)  # 在[-1, 1]范围上均匀生成1000个数
y1 = 2 * x + 1
y2 = x ** 2

plt.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 np

x = np.linspace(-1, 1, 1000)
y1 = 2 * x + 1
y2 = x ** 2

plt.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 Axes3D

flg = 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 np

plt.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 np

s1 = 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 np

date_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 pd

end = '\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 pd

def 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 np

end = '\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
"""



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值