NumPy Arrays in Python: Creation Guide

To create arrays using numpy, you first need to import the numpy library. Then you can use the functions provided by numpy to create arrays, as shown below:

  1. Create an array using the array function in numpy.
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)
  1. Create an array using the arange function from numpy.
import numpy as np

arr = np.arange(1, 10, 2)  # 从1开始,到10结束,步长为2
print(arr)
  1. Create an array filled with zeros using the zeros function from numpy.
import numpy as np

arr = np.zeros((2, 3))  # 创建一个2行3列的全零数组
print(arr)
  1. Create an array with all elements equal to one using the numpy function ones.
import numpy as np

arr = np.ones((3, 3))  # 创建一个3行3列的全一数组
print(arr)
  1. Create a random array using the random function in NumPy.
import numpy as np

arr = np.random.rand(2, 2)  # 创建一个2行2列的随机数组
print(arr)

These are some basic ways of creating arrays using numpy, you can further explore other functions and methods of the numpy library as needed.

bannerAds