以下是10个使用NumPy的示例,每个示例都带有输出结果:
- 创建NumPy数组:
import numpy as np
# 创建一个长度为5的一维数组,元素都是0
arr1 = np.zeros(5)
print(arr1)
# 创建一个2x3的二维数组,元素都是1
arr2 = np.ones((2, 3))
print(arr2)
# 创建一个3x3的单位矩阵
arr3 = np.eye(3)
print(arr3)
输出:
[0. 0. 0. 0. 0.]
[[1. 1. 1.]
[1. 1. 1.]]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
- 数组运算:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# 数组相加
result_add = arr1 + arr2
print(result_add)
# 数组相乘(对应元素相乘)
result_multiply = arr1 * arr2
print(result_multiply)
# 数组点积(矩阵乘法)
result_dot = np.dot(arr1, arr2)
print(result_dot)
输出:
[5 7 9]
[ 4 10 18]
32
- 数组索引和切片:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# 获取第三个元素
third_element = arr[2]
print(third_element)
# 获取第二到第四个元素(切片)
slice_arr = arr[1:4]
print(slice_arr)
# 修改元素值
arr[0] = 10
print(arr)
输出:
3
[2 3 4]
[10 2 3 4 5]
- 数组形状操作:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 获取数组形状
shape = arr.shape
print(shape)
# 转置数组
transposed_arr = arr.T
print(transposed_arr)
# 改变数组形状
reshaped_arr = arr.reshape(3, 2)
print(reshaped_arr)
输出:
(2, 3)
[[1 4]
[2 5]
[3 6]]
[[1 2]
[3 4]
[5 6]]
- 统计运算:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 计算数组均值
mean_value = np.mean(arr)
print(mean_value)
# 计算数组标准差
std_deviation = np.std(arr)
print(std_deviation)
# 计算数组累积和
cumsum = np.cumsum(arr)
print(cumsum)
输出:
3.5
1.707825127659933
[ 1 3 6 10 15 21]
- 数组拼接和分割:
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])
# 数组拼接
concatenated_arr = np.concatenate((arr1, arr2), axis=0)
print(concatenated_arr)
# 数组分割
split_arr = np.split(concatenated_arr, 2, axis=0)
print(split_arr)
输出:
[[1 2]
[3 4]
[5 6]]
[array([[1, 2]]), array([[3, 4],
[5, 6]])]
- 广播操作:
import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2
# 数组和标量相加(广播)
result_broadcast = arr1 + scalar
print(result_broadcast)
输出:
[[3 4 5]
[6 7 8]]
- 逻辑运算和布尔索引:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# 判断元素是否大于2
greater_than_2 = arr > 2
print(greater_than_2)
# 使用布尔索引获取符合条件的元素
filtered_arr = arr[arr > 2]
print(filtered_arr)
输出:
[False False True True True]
[3 4 5]
- 随机数生成:
import numpy as np
# 生成随机整数数组
random_int_arr = np.random.randint(1, 10, size=(2, 3))
print(random_int_arr)
# 生成随机浮点数数组
random_float_arr = np.random.rand(3, 2)
print(random_float_arr)
输出:
[[7 6 2]
[5 9 9]]
[[0.85574175 0.62360251]
[0.17683274 0.76652094]
[0.8326267 0.19824845]]
- 线性代数运算:
import numpy as np
# 创建矩阵
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# 矩阵乘法
matrix_product = np.dot(A, B)
print(matrix_product)
输出:
[[19 22]
[43 50]]
了解更多python项目开发,请关注我:Python提升课堂