Create Numpy Array: Quick Guide

To create an array using numpy, you first need to install and import the numpy library. Then, you can use the functions provided by the numpy library to create the array.

Here are some common numpy functions for creating arrays:

  1. By using the array() function in numpy, you can pass parameters such as lists, tuples, lists of lists, etc. to create a numpy array.
import numpy as np

arr1 = np.array([1, 2, 3])  # 创建一个一维数组
arr2 = np.array([[1, 2, 3], [4, 5, 6]])  # 创建一个二维数组
  1. Using the zeros() function in NumPy allows you to create an array filled with zeros of a specific shape.
arr = np.zeros((3, 4))  # 创建一个3行4列的全零数组
  1. By using the ones() function in numpy, you can create an array filled with ones of a specified shape.
arr = np.ones((2, 3))  # 创建一个2行3列的全一数组
  1. The arange() function in numpy allows you to create an array with a specified range and step size.
arr = np.arange(0, 10, 2)  # 创建一个从0到10(不包括10),步长为2的数组
  1. Using the linspace() function in numpy allows you to create an evenly spaced array with a specified start, end, and number of elements.
arr = np.linspace(0, 1, 5)  # 创建一个从0到1(包括1),共5个元素的等差数组

These are just some common methods for creating arrays in numpy, there are many more functions available for creating arrays of specific shapes and data types. You can refer to numpy’s official documentation for more detailed usage.

bannerAds