python学习_day6---数据分析numpy+matplotlib

一、numpy

1、读写文件

1>二进制文件读写

import numpy as np
"""
二进制文件、文本文件
"""
arr1 = np.arange(16).reshape(4, 4)
print(arr1)
"""
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
"""
# 1、数据保存,写文件 np.save 默认保存为二进制文件------仅保存单个数组
# 参数1:保存路径和文件名,可以不写后缀,默认为npy
# 参数2:要保存的数组
np.save("arr1", arr1)

# 2、读文件,加载文件. np.load------查看文件
# 参数1:路径和文件名,必须写后缀
arr_new = np.load("arr1.npy")
print(arr_new)
"""
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
"""
# 3、数据保存,可以将多个数组保存到一个文件中 np.savez
# 多个数组保存到npz文件,默认被组织为字典的形式
# key:arr_0  val1:第一个数组
# key:arr_1  val2:第二个数组
# ....

# 参数1:保存路径和文件名,可以不写后缀,默认为npz
# 其他参数:要保存的多个数组名
arr2 = np.zeros((2, 2))
np.savez("arr_all", arr1, arr2)

# 保存时,可以指定key
# np.savez("arr_all", a=arr1, b=arr2)

# 4、读取npz文件---np.load
# 参数:路径和文件名
arr_all = np.load("arr_all.npz")
print(arr_all) # <numpy.lib.npyio.NpzFile object at 0x000001F2F24A66A0>
# print无法查看,借助for循环查看
for tmp in arr_all:
    print(tmp)  
# arr_0  arr_1
# (默认结果是保存时给的key值,要是在保存时指定key值,则结果为自己指定的key值)

# 因为按照字典的方式被保存,所以可以使用字典的方式访问
# 按照字典的访问方式
# print("第一个数组", arr_all["arr_0"])
# print("第二个数组", arr_all["arr_1"])

2>文本文件读写

# 文本文件的读写(txt, csv(以逗号为分隔符))
# 写文件、保存文件,数组保存txt文件中  np.savetxt
# 参数1 保存的路径和文件名
# 参数2:保存的数组
# 参数3:保存的格式 fmt,默认为科学计数法'%1.8e'
# 参数4:分割符,delimiter, 默认是空格
np.savetxt("arr1.txt", arr1, fmt="%d", delimiter=",")
np.savetxt("arr1.csv", arr1, fmt="%d", delimiter=",")
# csv以,作为分隔符,用excel表格打开的时候,数据各占一个格,要是没用,分隔符,则一行数据存在一个excel格中

# 读文件、加载文件,np.loadtxt将文本文件 加载 为一个numpy数组
# 读文件的分隔符 需要和保存时一致 dtype默认float
res = np.loadtxt("arr1.txt", delimiter=",", dtype=int)
print("res\n", res, type(res))
"""
res
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]] <class 'numpy.ndarray'>
"""

2、数组去重

import numpy as np

# 去重 np.unique; 去重的同时 做升序排序
# 1、一维数组的去重
arr1 = np.array([1, 2, 3, 4, 6, 3, 2, 2, 1])
res = np.unique(arr1)
print("去重后\n", res)
"""
去重后
 [1 2 3 4 6]
"""
# 2、二维数组的去重
arr2 = np.array([["A", 1],
                 [1, 2],
                 [2, 3],
                 ["A", 1]])

# 如果不指定axis,对所有元素进行处理;
res = np.unique(arr2)
print("去重后\n", res)
"""
去重后
 ['1' '2' '3' 'A']
"""
# 去除重复的行 axis=0; 如果去除重复列 axis=1
res = np.unique(arr2, axis=0)
print("去重后\n", res)
"""
去重后
 [['1' '2']
 ['2' '3']
 ['A' '1']]
"""

3、数组重复

import numpy as np
"""
重复的两种形式:
repeat
tile
"""
arr = np.arange(9).reshape(3, 3)
print(arr)
"""
[[0 1 2]
 [3 4 5]
 [6 7 8]]
"""
# 1、repeat
# 如果不指定axis,对所有元素进行处理;
res = np.repeat(arr, repeats=3)
print("res\n", res)
"""
res
 [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8]
"""
# axis=0 每一行作为一个元素进行重复;行的方向 进行重复
res = np.repeat(arr, repeats=3, axis=0)
print("res\n", res)
"""
res
 [[0 1 2]
 [0 1 2]
 [0 1 2]
 [3 4 5]
 [3 4 5]
 [3 4 5]
 [6 7 8]
 [6 7 8]
 [6 7 8]]
"""
# axis=1,列的方向  进行重复
res = np.repeat(arr, repeats=3, axis=1)
print("res\n", res)
"""
res
 [[0 0 0 1 1 1 2 2 2]
 [3 3 3 4 4 4 5 5 5]
 [6 6 6 7 7 7 8 8 8]]
"""

# 2、tile
# 将数组A作为一个整体,构建一个新数组(数组A作为其元素)
res = np.tile(arr, (1, 2))
print("res\n", res)
"""
res
 [[0 1 2 0 1 2]
 [3 4 5 3 4 5]
 [6 7 8 6 7 8]]
"""

4、数组排序

1>一维数组的排序

import numpy as np

# 1、一维数组的排序
# 1>np.sort()
arr = np.array([9, 8, 7, 1, 2, 3])
res = np.sort(arr)
print("原始数组", arr) # 原始数组 [9 8 7 1 2 3]
print("排序后的结果", res) # 排序后的结果 [1 2 3 7 8 9]

# 2>np.argsort()  # 如果包含arg,通常返回索引相关内容
# 升序排序,但是返回的是索引
res = np.argsort(arr)
print("res", res) # res [3 4 5 2 1 0]

# 按照列表法进行访问
new_arr = arr[res]
print("new_arr", new_arr) # new_arr [1 2 3 7 8 9]
new_arr = arr[res[::-1]]
print("new_arr", new_arr) # new_arr [9 8 7 3 2 1]

2>二维数组的排序

# 2、二维数组的排序
np.random.seed(1)
arr2 = np.random.randint(low=2, high=7, size=(3, 4))
print(arr2)
"""
[[5 6 2 3]
 [5 2 2 3]
 [6 6 3 4]]
"""
# axis默认是-1 在二维数组中代表列的方向
new_arr2 = np.sort(arr2)
print("排序后结果\n", new_arr2)
"""
排序后结果
 [[2 3 5 6]
 [2 2 3 5]
 [3 4 6 6]]
"""
# 行的方向进行排序axis =0
new_arr2 = np.sort(arr2, axis=0)
print("排序后结果\n", new_arr2)
"""
排序后结果
 [[5 2 2 3]
 [5 6 2 3]
 [6 6 3 4]]
"""

二、matplotlib

1、折线图

import matplotlib.pyplot as plt
import numpy as np
# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False

# 一、创建画布
plt.figure()

# 二、画图
# 1、准备x轴的数据
x = np.arange(1, 8)
# 2、准备y轴的数据
y = [15, 20, 22, 23, 20, 18, 16]
y_low = [10, 17, 12, 13, 9, 8, 6]

# 折线图 plot
# marker 点的样式 o 圆圈
# markerfacecolor 点内部的颜色
plt.plot(x, y, color="#A52A2A",
         linestyle=':',
         marker="o",
         markersize=12,
         markerfacecolor="b",
         markeredgecolor="#006400")
plt.plot(x, y_low,
         color="#00CED1",
         linestyle='--',
         marker="*",
         markersize=9,
         markerfacecolor="r",
         markeredgecolor="#006400"
         )

# 增加描述性信息
# 增加标题
plt.title("the weather info 天气信息")
# 增加X轴的刻度
xtick = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
# plt.xticks(x[::2], xtick[::2], rotation=45)
plt.xticks(x, xtick, rotation=45)
# 修改Y轴的刻度,重新换刻度
plt.yticks(np.arange(-20, 45, 5))

# 增加x、y轴的显示信息
plt.xlabel("日期")
plt.ylabel("温度")

# 增加图例
# 字符串列表的形式
plt.legend(["最高温度", "最低温度"])

# 增加标注信息
# plt.text(1, 15+1, "15℃")
for i, j in zip(x, y):
    plt.text(i,
             j + 1, # 高一点要不被点覆盖了就
             "%d℃" % j, # 格式化
             horizontalalignment='center' # 居中
             )

for i, j in zip(x, y_low):
    plt.text(i,
             j - 2,
             "%d℃" % j,
             horizontalalignment='center'
             )

# 三、显示和保存图
# 保存需要在显示之前
# plt.savefig("天气预报图.jpg")  # 要保存的文件名
plt.show()

在这里插入图片描述

2、散点图

import matplotlib.pyplot as plt
import numpy as np
# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False

# 一、创建画布
plt.figure()

# 二、画图
# 创建数据
x = np.arange(0, 2 * np.pi, 0.1)
y = np.sin(x)
# 散点图的绘制
plt.scatter(x, y)

# 三、显示图
plt.show()

在这里插入图片描述

3、子图

import matplotlib.pyplot as plt
import numpy as np

# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False

# 一、创建画布
# figsize 英寸 设置画布大小
# dpi每英寸的像素值
# 如果创建子图的话,必须显示创建画布
fig = plt.figure(figsize=(12, 10), dpi=100)
# 通常设置为0-1.
# wspace 子图之间宽度间距.如果设置为0.5,宽度间隔为子图宽度的50%
# hspace 子图之间高度间距,如果设置0.9, 高度间隔为子图高度的90%
fig.subplots_adjust(wspace=0.5, hspace=0.9)

x = np.arange(0, 2 * np.pi, 0.2)

fig.add_subplot(2, 1, 1)  # 2行1列第一个子图
# 第一个图的绘制
y1 = np.sin(x)
plt.scatter(x, y1)
# fig.add_subplot(2, 2, 1)  # 2行2列第一个子图
# # 第一个图的绘制
# y1 = np.sin(x)
# plt.scatter(x, y1)
# fig.add_subplot(2, 2, 2)  # 2行2列第2个子图
# # 第2个图的绘制
# y2 = np.cos(x)
# plt.plot(x, y2)

fig.add_subplot(2, 2, 3)  # 2行2列第3个子图
# 第3个图的绘制
y3 = x ** 2
plt.plot(x, y3)

fig.add_subplot(2, 2, 4)  # 2行2列第4个子图
# 第4个图的绘制
x4 = np.arange(-np.pi, np.pi, 0.5)
y4 = np.cos(x4)
plt.scatter(x4, y4)

# plt.savefig("子图.jpg")
plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45800653/article/details/121568025