python numpy库最常用的10个用法|干货分享

  1. 创建数组:
import numpy as np
# 创建一个一维数组
a = np.array([1, 2, 3, 4, 5])
print(a)
# 创建一个二维数组
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
  1. 数组的计算:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# 数组加法
c = a + b
print(c)
# 数组乘法
d = a * b
print(d)
# 数组平方
e = np.square(a)
print(e)
  1. 数组形状操作:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
# 获取数组形状
print(a.shape)
# 转置数组
b = np.transpose(a)
print(b)
# 改变数组形状
c = np.reshape(a, (3, 2))
print(c)
  1. 数组的切片和索引:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# 数组切片
b = a[1:4]
print(b)
# 数组索引
c = a[2]
print(c)
  1. 数组统计操作:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
# 计算数组的和
b = np.sum(a)
print(b)
# 计算数组的均值
c = np.mean(a)
print(c)
# 计算数组的最大值
d = np.max(a)
print(d)
# 计算数组的最小值
e = np.min(a)
print(e)
  1. 数组的排序:
import numpy as np
a = np.array([3, 2, 1, 4, 6, 5])
# 对数组进行排序
b = np.sort(a)
print(b)
  1. 数组的拼接和拆分:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
# 数组的垂直拼接
c = np.vstack((a, b))
print(c)
# 数组的水平拼接
d = np.hstack((a, b))
print(d)
# 数组的拆分
e, f = np.split(a, 2)
print(e)
print(f)
  1. 数组的重复操作:
import numpy as np
a = np.array([1, 2, 3])
# 数组的重复
b = np.repeat(a, 3)
print(b)
# 数组的扩展重复
c = np.tile(a, 3)
print(c)
  1. 数组的布尔运算:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# 布尔条件运算
b = a > 2
print(b)
# 布尔索引
c = a[b]
print(c)
  1. 数组的随机数生成:
import numpy as np
# 生成一个随机的一维数组
a = np.random.rand(5)
print(a)
# 生成一个随机的二维数组
b = np.random.rand(2, 3)
print(b)

已发布

分类

标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注