day18学习numpy库

一、NumPy库

11.数组操作

11.1数组变维

11.1.1 reshape方法

把一个数组转化为指定的形状(改变维度)

  • 示例:
import numpy as np

a = np.array([1,2,3,4,5, 6])
print(a.ndim)  # 输出维度 1
b = a.reshape(2,3)
# 输出b的维度
print(b.ndim)  # 输出维度 2
11.1.2 flat方法

返回一个迭代器,循环输出数组的每一个元素(以一维的状态输出)

  • 示例:
import numpy as np
a = np.array([1, 2, 3], [4, 5, 6])
for i in a.flat:
    print(i, end=' ')
# 输出 1 2 3 4 5 6

11.2数组转置

11.2.1 np.transpose() 方法

将数组的维度值进行对换,比如二维数组维度(2,4)使用该方法后为(4,2)

  • 示例:
import numpy as np

array_one = np.arange(12).reshape(3, 4)
print("原数组:")
print(array_one)
print("使用transpose()函数后的数组:")
print(np.transpose(array_one))
  • 输出:
原数组:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
使用transpose()函数后的数组:
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]
11.2.2 list . T 属性

与transpose方法效果一样

  • 示例
import numpy as np
array_one = np.arange(12).reshape(3, 4)
print("使用T属性后的数组:")
print(array_one.T)
  • 输出
使用T属性后的数组:
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]

11.3升维和降维

11.3.1升维expand_dims( )
  • 参数1:输入数组 参数2:axis=新轴插入的位置

  • 在指定位置插入新的轴,从而扩展数组的维度

  • 0是横向,1是纵向

  • 示例

import numpy as np

# 创建一个一维数组
a = np.array([1, 2, 3])
print(a.shape)  # 输出: (3,)

# 在第 0 维插入新维度
b = np.expand_dims(a, axis=0)
print(b)
# 输出:
# [[1 2 3]]
print(b.shape)  # 输出: (1, 3)

# 在第 1 维插入新维度
c = np.expand_dims(a, axis=1)
print(c)
# 输出:
# [[1]
#  [2]
#  [3]]
print(c.shape)  # 输出: (3, 1)
11.3.2降维squeeze( )
  • 参数1:输入数组 参数2:axis=删除的位置(必须为1)
  • 删除数组中维度为 1 的项
  • 示例:
import numpy as np

# 创建一个数组
c = np.array([[[1, 2, 3]]])
print(c.shape)  # 输出: (1, 1, 3)

# 移除第 0 维
d = np.squeeze(c, axis=0)
print(d)
# 输出:
# [[1 2 3]]
print(d.shape)  # 输出: (1, 3)

# 移除第 1 维
e = np.squeeze(c, axis=1)
print(e)
# 输出:
# [[1 2 3]]
print(e.shape)  # 输出: (1, 3)

# 移除第 2 维
f = np.squeeze(c, axis=2)
print(f)
# 输出:
# ValueError: cannot select an axis to squeeze out which has size not equal to one

11.4连接数组

vstack() 和 hstack() 要求堆叠的数组在某些维度上具有相同的形状。如果维度不一致,将无法执行堆叠操作。

11.4.1 hstack(tup 1,tup2)
  • tup:可以是元组、列表、numpy数组,返回值是numpy数组
  • 水平方向拼接、
  • 示例:
import numpy as np

# 创建两个形状不同的数组,行数一致
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5], [6]])
print(arr1.shape) 	# (2, 2)
print(arr2.shape)	# (2, 1)

# 使用 hstack 水平堆叠数组
result = np.hstack((arr1, arr2))
print(result)
# 输出:
# [[1 2 5]
#  [3 4 6]]
11.4.2 vstack(tup1,tup2)
  • tup:可以是元组、列表、numpy数组,返回值是numpy数组
  • 垂直方向拼接
  • 示例:
# 创建两个一维数组
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# 使用 vstack 垂直堆叠数组
result = np.vstack((arr1, arr2))
print(result)
# 输出:
# [[1 2 3]
#  [4 5 6]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值