NumPy是Python中一个强大的库,主要用于处理大型多维数组和矩阵的数学运算。处理数组翻转与变形是NumPy的常用功能。
1.对多维数组翻转
n = np.random.randint(0,100,size=(5,6))
n
# 执行结果
array([[ 9, 48, 20, 85, 19, 93],
[ 1, 63, 20, 25, 19, 44],
[15, 70, 12, 58, 4, 11],
[85, 51, 86, 28, 31, 27],
[64, 15, 33, 97, 59, 56]])
# 行翻转
n[::-1]
# 执行结果
array([[64, 15, 33, 97, 59, 56],
[85, 51, 86, 28, 31, 27],
[15, 70, 12, 58, 4, 11],
[ 1, 63, 20, 25, 19, 44],
[ 9, 48, 20, 85, 19, 93]])
# 列翻转:相对于是对第二个维度做翻转
n[:,::-1]
# 执行结果
array([[93, 19, 85, 20, 48, 9],
[44, 19, 25, 20, 63, 1],
[11, 4, 58, 12, 70, 15],
[27, 31, 28, 86, 51, 85],
[56, 59, 97, 33, 15, 64]])
2.把图片翻转
# 数据分析三剑客
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# python.png
# 图片:其实时数字组成的,三维数组
# RGB:红Red,绿Green,蓝Blue
# RGB范围:0-255
# plt.imread:读取图片的数据
pyimg = plt.imread("python.png")
pyimg
# 显示原图
plt.imshow(pyimg)
# 行翻转:上下翻转
plt.imshow(pyimg[::-1])
# 列翻转:左右翻转
plt.imshow(pyimg[:,::-1])
# 对颜色翻转:RGB => BGR
plt.imshow(pyimg[:,:,::-1])
# 模糊处理
plt.imshow(pyimg[::10,::10,::-1])
3.数组变形
-
使用reshape函数
# 创建一个20个元素的一维数组
n = np.arange(1,21)
n
# 执行结果
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20])
# 查看形状
print(n.shape)
# 执行结果
(20,)
# reshape:将数组改变形状
# 将n变成4行5列的二维数组
n2 = np.reshape(n,(4,5))
print(n2)
# 执行结果
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
print(n2.shape)
# 执行结果
(4, 5)
# 将n2变成5行4列的二维数组
# n2.reshape(5,4)
print(n2.reshape((5,4)))
# 执行结果
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]]
# 注意:变形的过程中需要保持元素个数一致
# n2.reshape((5,5)) # 20个元素变形成25个则报错
# 还原成一维数组
print(n2.reshape(20))
# 执行结果
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
print(n2.reshape(-1))
# 执行结果
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
# 使用-1:表示任意剩余维度长度
print(n2.reshape(4,-1))
# 执行结果
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
print(n2.reshape(5,-1))
# 执行结果
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]]
print(n2.reshape(-1,2))
# 执行结果
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]
[13 14]
[15 16]
[17 18]
[19 20]]
print(n2.reshape(-1,1))
# 执行结果
[[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]
[17]
[18]
[19]
[20]]
# 不能使用两个-1
# print(n2.reshape(-1,-1))
n2.reshape(2,-1,2)
# 执行结果
array([[[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10]],
[[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20]]])