ndarray
(n-dimensional array),这是一个同质数据类型的多维数组。
下面是一些关于 NumPy 使用的详细说明:
确保已经安装了 NumPy。可以通过 pip 来安装:
pip install numpy
通常会使用别名 np
来导入 NumPy:
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
# 输出: [1 2 3]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
# 输出:
# [[1 2 3]
# [4 5 6]]
全零数组 (zeros
):
arr = np.zeros((2, 3))
print(arr)
# 输出:
# [[0. 0. 0.]
# [0. 0. 0.]]
全一数组 (ones
):
arr = np.ones((2, 3))
print(arr)
# 输出:
# [[1. 1. 1.]
# [1. 1. 1.]]
空数组 (empty
):
arr = np.empty((2, 3))
print(arr)
# 输出:
# [[0. 0. 0.] # 数值不确定
# [0. 0. 0.]]
等差数组 (arange
):
arr = np.arange(0, 10, 2)
print(arr)
# 输出: [0 2 4 6 8]
等比数组 (linspace
):
arr = np.linspace(0, 10, 5)
print(arr)
# 输出: [ 0. 2.5 5. 7.5 10. ]
随机数组 (random.rand
):
arr = np.random.rand(2, 3)
print(arr)
# 输出:
# [[0.912 0.544 0.365] # 数值随机
# [0.761 0.621 0.842]]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # 输出: (2, 3)
print(arr.size) # 输出: 6
arr = np.array([1, 2, 3], dtype=np.float32)
print(arr.dtype) # 输出: float32
arr = np.array([1, 2, 3])
arr = arr.astype(np.float32)
print(arr.dtype) # 输出: float32
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1]) # 输出: 2
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, :2]) # 输出: [1 2]
arr = np.array([1, 2, 3])
arr = arr.reshape(3, 1)
print(arr)
# 输出:
# [[1]
# [2]
# [3]]
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print(c)
# 输出: [1 2 3 4 5 6]
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.split(arr, 3)
print(newarr)
# 输出: [array([1, 2]), array([3, 4]), array([5, 6])]
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b
print(c)
# 输出: [5 7 9]
a = np.array([1, 2, 3])
b = 2
c = a * b
print(c)
# 输出: [2 4 6]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(arr)) # 输出: 21
print(np.mean(arr)) # 输出: 3.5
print(np.std(arr)) # 输出: 1.707825127659933
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.max(arr)) # 输出: 6
print(np.min(arr)) # 输出: 1
arr = np.array([3, 1, 2])
sorted_arr = np.sort(arr)
print(sorted_arr)
# 输出: [1 2 3]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1]) # 输出: 2
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1:3]) # 输出: [2 3]
arr = np.array([[1, 2, 3], [4, 5, 6]])
rows = np.array([0, 1])
cols = np.array([1, 2])
print(arr[rows, cols]) # 输出: [2 6]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[arr > 3]) # 输出: [4 5 6]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.where(arr > 3, arr, -1)) # 输出: [[-1 -1 -1] [ 4 5 6]]
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.dot(a, b)
print(c)
# 输出:
# [[19 22]
# [43 50]]
a = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
x = np.linalg.solve(a, b)
print(x)
# 输出: [ -4. 4.5]
a = np.array([[1, 2], [3, 4]])
inv_a = np.linalg.inv(a)
print(inv_a)
# 输出:
# [[-2. 1. ]
# [ 1.5 -0.5]]