How to create NumPy arrays in Python?

In the NumPy library of Python, you can use the numpy.array() function to create an array. Arrays can be multi-dimensional and can contain different types of data such as integers, floats, and complex numbers.

Here are some common ways to create NumPy arrays:

  1. Creating arrays using Python lists.
import numpy as np

a = np.array([1, 2, 3, 4, 5])  # 一维数组
b = np.array([[1, 2, 3], [4, 5, 6]])  # 二维数组
c = np.array([1, 2, 3], dtype=float)  # 指定数据类型
  1. Create arrays of special types using functions in NumPy.
import numpy as np

a = np.zeros((3, 3))  # 全零数组
b = np.ones((2, 2))  # 全一数组
c = np.eye(3)  # 单位矩阵
d = np.arange(0, 10, 2)  # 指定范围内的等差数列
e = np.linspace(0, 1, 5)  # 指定范围内的等间隔数列
f = np.random.rand(3, 3)  # 随机数组
  1. Create a new array using the shape of another array.
import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.zeros_like(a)  # 以a的形状创建全零数组
c = np.ones_like(a)  # 以a的形状创建全一数组
d = np.empty_like(a)  # 以a的形状创建空数组

These are just some common methods for creating NumPy arrays, and there are many other methods to create arrays of different types based on requirements.

bannerAds