How do you use np.array() in Python?

Using the np.array() function in Python allows you to create a multi-dimensional array. The np.array() function takes a sequence (such as a list or tuple) as a parameter and returns a multi-dimensional array containing the elements of that sequence.

Here is an example of how to use the np.array() function:

import numpy as np

# 通过列表创建一维数组
arr1 = np.array([1, 2, 3])
print(arr1)  # 输出: [1 2 3]

# 通过列表创建二维数组
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2)
# 输出:
# [[1 2 3]
#  [4 5 6]]

# 通过元组创建二维数组
arr3 = np.array(((1, 2, 3), (4, 5, 6)))
print(arr3)
# 输出:
# [[1 2 3]
#  [4 5 6]]

In the above example, we first import the numpy library and then create one-dimensional and two-dimensional arrays using the np.array() function. It is important to note that the elements of multi-dimensional arrays can be of any type, but are typically numerical.

bannerAds