温馨提示×

numpy创建数组的方法是什么

小亿
82
2024-04-23 17:05:49
栏目: 编程语言

使用NumPy创建数组的方法有多种,以下是其中一些常用的方法:

  1. 使用 np.array() 函数从列表或元组中创建数组。
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
  1. 使用 np.zeros() 函数创建指定形状的全零数组。
zeros_arr = np.zeros((2, 3))  # 创建一个2行3列的全零数组
  1. 使用 np.ones() 函数创建指定形状的全一数组。
ones_arr = np.ones((3, 4))  # 创建一个3行4列的全一数组
  1. 使用 np.arange() 函数创建指定范围的等差数组。
range_arr = np.arange(0, 10, 2)  # 创建一个从0到10,步长为2的数组
  1. 使用 np.linspace() 函数创建指定范围的等间距数组。
linspace_arr = np.linspace(0, 10, 5)  # 创建一个从0到10,共5个元素的等间距数组
  1. 使用 np.eye() 函数创建单位矩阵。
eye_arr = np.eye(3)  # 创建一个3阶的单位矩阵
  1. 使用 np.random.rand()np.random.randn() 函数创建随机数组。
rand_arr = np.random.rand(2, 3)  # 创建一个2行3列的随机数组
randn_arr = np.random.randn(3, 4)  # 创建一个3行4列的符合正态分布的随机数组

0