【Python】一文学会使用Numpy库(数组)

自由坦荡的智能 2025-02-15 03:22:18

创建 NumPy 数组

创建一个数组:

import numpy as nparray = np.array([1, 2, 3, 4, 5])2. 零或一的数组

创建一个填充零的数组:

zeros = np.zeros((3, 3)) # A 3x3 array of zerosones = np.ones((2, 4)) # A 2x4 array of ones3. 创建一个数字范围

创建一个数字序列:

range_array = np.arange(10, 50, 5) # From 10 to 50, step by 54. 创建线性间隔数组

创建一系列值,这些值在两个界限之间均匀分布:

linear_spaced = np.linspace(0, 1, 5) # 5 values from 0 to 15. 重新塑形数组

将数组形状转换,改变其维度:

reshaped = np.arange(9).reshape(3, 3) # Reshape a 1D array into a 3x3 2D array6. 基本数组操作

对数组执行元素操作:

a = np.array([1, 2, 3])b = np.array([4, 5, 6])sum = a + b # Element-wise additiondifference = b - a # Element-wise subtractionproduct = a * b # Element-wise multiplication7. 矩阵乘法

基本点积运算:

result = np.dot(a.reshape(1, 3), b.reshape(3, 1)) # Dot product of a and b8. 访问数组元素

访问数组元素的有用语法:

element = a[2] # Retrieve the third element of array 'a'row = reshaped[1, :] # Retrieve the second row of 'reshaped'9. 布尔索引

通过条件筛选器过滤数组元素:

filtered = a[a > 2] # Elements of 'a' greater than 210. 聚合与统计

统计操作在 NumPy 数组上:

mean = np.mean(a)maximum = np.max(a)sum = np.sum(a)
0 阅读:0
自由坦荡的智能

自由坦荡的智能

感谢大家的关注