- 90个NumPy案例">90个NumPy案例
- 有多个条件时替换 Numpy 数组中的元素
- 在 Python 中找到 Numpy 数组的维度
- 两个条件过滤 NumPy 数组
- 对最后一列求和
- 满足条件,则替换 Numpy 元素
- 从 Nump y数组中随机选择两行
- 以给定的精度漂亮地打印一个 Numpy 数组
- 提取 Numpy 矩阵的前 n 列
- 从 NumPy 数组中删除值
- 将满足条件的项目替换为 Numpy 数组中的另一个值
- 如何根据 Pandas 列中的值从 DataFrame 中选择或过滤行
- 创建 3D NumPy 零数组
- 计算 NumPy 数组中每一行的总和
- 打印没有科学记数法的 NumPy 数组
- 获取numpy数组中所有NaN值的索引列表
- 检查 NumPy 数组中的所有元素都是 NaN
- 将列表添加到 Python 中的 NumPy 数组
- 在 Numpy 中抑制科学记数法
- 将具有 12 个元素的一维数组转换为 3 维数组
- 检查 NumPy 数组是否为空
- 在 Python 中重塑 3D 数组
- 在 Python 中重复 NumPy 数组中的一列
- 在 NumPy 数组中找到跨维度的平均值
- 检查 NumPy 数组中的 NaN 元素
- 格式化 NumPy 数组的打印方式
- 乘以Numpy数组的每个元素
- 在 NumPy 中生成随机数
- Numpy 将具有 8 个元素的一维数组转换为 Python 中的二维数组
- 在 Python 中使用 numpy.all()
- 将一维数组转换为二维数组
- 计算 NumPy 数组中唯一值的频率
- 在一列中找到平均值
- 在 Numpy 数组的长度、维度、大小
- 在 NumPy 数组中找到最大值的索引
- 按降序对 NumPy 数组进行排序
- 按降序对 Numpy 进行排序
- Numpy 从二维数组中获取随机的一组行
- 将 Numpy 数组转换为 JSON
- 检查 NumPy 数组中是否存在值
- 创建一个 3D NumPy 数组
- 在numpy中将字符串数组转换为浮点数数组
- 从 Python 的 numpy 数组中随机选择
- 不截断地打印完整的 NumPy 数组
- 将 Numpy 转换为列表
- 将字符串数组转换为浮点数数组
- 计算 NumPy 数组中每一列的总和
- 使用 Python 中的值创建 3D NumPy 数组
- 计算不同长度的 Numpy 数组的平均值
- 从 Numpy 数组中删除 nan 值
- 向 NumPy 数组添加一列
- 在 Numpy Array 中打印浮点值时如何抑制科学记数法
- Numpy 将 1d 数组重塑为 1 列的 2d 数组
- 初始化 NumPy 数组
- 创建重复一行
- 将 NumPy 数组附加到 Python 中的空数组
- 找到 Numpy 数组的平均值
- 检测 NumPy 数组是否包含至少一个非数字值
- 在 Python 中附加 NumPy 数组
- 使用 numpy.any()
- 获得 NumPy 数组的转置
- 获取和设置NumPy数组的数据类型
- 获得NumPy数组的形状
- 获得 1、2 或 3 维 NumPy 数组
- 重塑 NumPy 数组
- 调整 NumPy 数组的大小
- 将 List 或 Tuple 转换为 NumPy 数组
- 使用 arange 函数创建 NumPy 数组s
- 使用 linspace() 创建 NumPy 数组
- NumPy 日志空间数组示例
- 创建 Zeros NumPy 数组
- NumPy One 数组示例
- NumPy 完整数组示例
- NumPy Eye 数组示例
- NumPy 生成随机数数组
- NumPy 标识和对角线数组示例
- NumPy 索引示例
- 多维数组中的 NumPy 索引
- NumPy 单维切片示例
- NumPy 数组中的多维切片
- 翻转 NumPy 数组的轴顺序
- NumPy 数组的连接和堆叠
- NumPy 数组的算术运算
- NumPy 数组上的标量算术运算
- NumPy 初等数学函数
- NumPy Element Wise 数学运算
- NumPy 聚合和统计函数
- Where 函数的 NumPy 示例
- Select 函数的 NumPy 示例
- 选择函数的 NumPy 示例
- NumPy 逻辑操作,用于根据给定条件从数组中选择性地选取值
- 标准集合操作的 NumPy 示例
90个NumPy案例
- 有多个条件时替换 Numpy 数组中的元素
- 将所有大于 30 的元素替换为 0
- 将大于 30 小于 50 的所有元素替换为 0
- 给所有大于 40 的元素加 5
- 用 Nan 替换数组中大于 25 的所有元素
- 将数组中大于 25 的所有元素替换为 1,否则为 0
- 在 Python 中找到 Numpy 数组的维度
- 两个条件过滤 NumPy 数组
- Example 1
- Example 2
- Example 3
- Example 4
- Example 5
- 对最后一列求和
- 第一列总和
- 第二列总和
- 第一列和第二列的总和
- 最后一列的总和
- 满足条件,则替换 Numpy 元素
- 将所有大于 30 的元素替换为 0
- 将大于 30 小于 50 的所有元素替换为 0
- 给所有大于 40 的元素加 5
- 用 Nan 替换数组中大于 25 的所有元素
- 将数组中大于 25 的所有元素替换为 1,否则为 0
- 从 Nump y数组中随机选择两行
- Example 1
- Example 2
- Example 3
- 以给定的精度漂亮地打印一个 Numpy 数组
- Example 1
- Example 2
- Example 3
- Example 4
- Example 5
- 提取 Numpy 矩阵的前 n 列
- 列范围1
- 列范围2
- 列范围3
- 特定列
- 特定行和列
- 从 NumPy 数组中删除值
- Example 1
- Example 2
- Example 3
- 将满足条件的项目替换为 Numpy 数组中的另一个值
- 将所有大于 30 的元素替换为 0
- 将大于 30 小于 50 的所有元素替换为 0
- 给所有大于 40 的元素加 5
- 用 Nan 替换数组中大于 25 的所有元素
- 将数组中大于 25 的所有元素替换为 1,否则为 0
- 对 NumPy 数组中的所有元素求和
- 创建 3D NumPy 零数组
- 计算 NumPy 数组中每一行的总和
- 打印没有科学记数法的 NumPy 数组
- 获取numpy数组中所有NaN值的索引列表
- 检查 NumPy 数组中的所有元素都是 NaN
- 将列表添加到 Python 中的 NumPy 数组
- 在 Numpy 中抑制科学记数法
- 将具有 12 个元素的一维数组转换为 3 维数组
- Example 1
- Example 2
- Example 3
- Example 4
- 检查 NumPy 数组是否为空
- 在 Python 中重塑 3D 数组
- Example 1
- Example 2
- Example 3
- Example 4
- 在 Python 中重复 NumPy 数组中的一列
- 在 NumPy 数组中找到跨维度的平均值
- 检查 NumPy 数组中的 NaN 元素
- 格式化 NumPy 数组的打印方式
- Example 1
- Example 2
- Example 3
- Example 4
- Example 5
- 乘以Numpy数组的每个元素
- Example 1
- Example 2
- Example 3
- Example 4
- 在 NumPy 中生成随机数
- Example 1
- Example 2
- Example 3
- Numpy 将具有 8 个元素的一维数组转换为 Python 中的二维数组
- 4 行 2 列
- 2 行 4 列
- 在 Python 中使用 numpy.all()
- 将一维数组转换为二维数组
- 4 行 2 列
- 2 行 4 列
- Example 3
- 通过添加新轴将一维数组转换为二维数组
- Example 5
- 计算 NumPy 数组中唯一值的频率
- 在一列中找到平均值
- 在 Numpy 数组的长度、维度、大小
- Example 1
- Example 2
- 在 NumPy 数组中找到最大值的索引
- 按降序对 NumPy 数组进行排序
- 按降序对 Numpy 进行排序
- 按降序对 2D Numpy 进行排序
- 按降序对 Numpy 进行排序
- Numpy 从二维数组中获取随机的一组行
- Example 1
- Example 2
- Example 3
- 将 Numpy 数组转换为 JSON
- 检查 NumPy 数组中是否存在值
- 创建一个 3D NumPy 数组
- 在numpy中将字符串数组转换为浮点数数组
- 从 Python 的 numpy 数组中随机选择
- Example 1
- Example 2
- Example 3
- 不截断地打印完整的 NumPy 数组
- 将 Numpy 转换为列表
- 将字符串数组转换为浮点数数组
- 计算 NumPy 数组中每一列的总和
- 使用 Python 中的值创建 3D NumPy 数组
- 计算不同长度的 Numpy 数组的平均值
- 从 Numpy 数组中删除 nan 值
- Example 1
- Example 2
- 向 NumPy 数组添加一列
- 在 Numpy Array 中打印浮点值时如何抑制科学记数法
- Numpy 将 1d 数组重塑为 1 列的 2d 数组
- 初始化 NumPy 数组
- 创建重复一行
- 将 NumPy 数组附加到 Python 中的空数组
- 找到 Numpy 数组的平均值
- 计算每列的平均值
- 计算每一行的平均值
- 仅第一列的平均值
- 仅第二列的平均值
- 检测 NumPy 数组是否包含至少一个非数字值
- 在 Python 中附加 NumPy 数组
- 使用 numpy.any()
- 获得 NumPy 数组的转置
- 获取和设置NumPy数组的数据类型
- 获得NumPy数组的形状
- 获得 1、2 或 3 维 NumPy 数组
- 重塑 NumPy 数组
- 调整 NumPy 数组的大小
- 将 List 或 Tuple 转换为 NumPy 数组
- 使用 arange 函数创建 NumPy 数组
- 使用 linspace() 创建 NumPy 数组
- NumPy 日志空间数组示例
- 创建 Zeros NumPy 数组
- NumPy One 数组示例
- NumPy 完整数组示例
- NumPy Eye 数组示例
- NumPy 生成随机数数组
- NumPy 标识和对角线数组示例
- NumPy 索引示例
- 多维数组中的 NumPy 索引
- NumPy 单维切片示例
- NumPy 数组中的多维切片
- 翻转 NumPy 数组的轴顺序
- NumPy 数组的连接和堆叠
- NumPy 数组的算术运算
- NumPy 数组上的标量算术运算
- NumPy 初等数学函数
- NumPy Element Wise 数学运算
- NumPy 聚合和统计函数
- Where 函数的 NumPy 示例
- Select 函数的 NumPy 示例
- 选择函数的 NumPy 示例
- NumPy 逻辑操作,用于根据给定条件从数组中选择性地选取值
- 标准集合操作的 NumPy 示例
有多个条件时替换 Numpy 数组中的元素
将所有大于 30 的元素替换为 0
```python import numpy as np
the_array = np.array([49, 7, 44, 27, 13, 35, 71])
an_array = np.where(the_array > 30, 0, the_array) print(an_array)
<a name="dY5xC"></a>#### OutPut```python[ 0 7 0 27 13 0 0]
将大于 30 小于 50 的所有元素替换为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where((the_array > 30) & (the_array < 50), 0, the_array)print(an_array)
OutPut
[ 0 7 0 27 13 0 71]
给所有大于 40 的元素加 5
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 40, the_array + 5, the_array)print(an_array)
OutPut
0 A1 A2 A3 Adtype: object
用 Nan 替换数组中大于 25 的所有元素
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 25, np.NaN, the_array)print(an_array)
OutPut
[nan 7. nan nan 13. nan nan]
将数组中大于 25 的所有元素替换为 1,否则为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.asarray([0 if val < 25 else 1 for val in the_array])print(an_array)
OutPut
[1 0 1 1 0 1 1]
在 Python 中找到 Numpy 数组的维度
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])print(arr.ndim)arr = np.array([[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]])print(arr.ndim)arr = np.array([[[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]]])print(arr.ndim)
OutPut
123
两个条件过滤 NumPy 数组
Example 1
import numpy as npthe_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])filter_arr = np.logical_and(np.greater(the_array, 3), np.less(the_array, 8))print(the_array[filter_arr])
OutPut
[4 5 6 7]
Example 2
import numpy as npthe_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])filter_arr = np.logical_or(the_array < 3, the_array == 4)print(the_array[filter_arr])
OutPut
[1 2 4]
Example 3
import numpy as npthe_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])filter_arr = np.logical_not(the_array > 1, the_array < 5)print(the_array[filter_arr])
OutPut
[1]
Example 4
import numpy as npthe_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])filter_arr = np.logical_or(the_array == 8, the_array < 5)print(the_array[filter_arr])
OutPut
[1 2 3 4 8]
Example 5
import numpy as npthe_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])filter_arr = np.logical_and(the_array == 8, the_array < 5)print(the_array[filter_arr])
OutPut
[]
对最后一列求和
第一列总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr[:, 0].sum()print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]22
第二列总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr[:, 1].sum()print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]26
第一列和第二列的总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr[:, 0:2].sum()print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]48[]
最后一列的总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr[:, -1].sum()print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]30
满足条件,则替换 Numpy 元素
将所有大于 30 的元素替换为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 30, 0, the_array)print(an_array)
OutPut
[ 0 7 0 27 13 0 0]
将大于 30 小于 50 的所有元素替换为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where((the_array > 30) & (the_array < 50), 0, the_array)print(an_array)
OutPut
[ 0 7 0 27 13 0 71][]
给所有大于 40 的元素加 5
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 40, the_array + 5, the_array)print(an_array)
OutPut
[54 7 49 27 13 35 76]
用 Nan 替换数组中大于 25 的所有元素
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 25, np.NaN, the_array)print(an_array)
OutPut
[nan 7. nan nan 13. nan nan]
将数组中大于 25 的所有元素替换为 1,否则为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.asarray([0 if val < 25 else 1 for val in the_array])print(an_array)
OutPut
[1 0 1 1 0 1 1]
从 Nump y数组中随机选择两行
Example 1
import numpy as np# create 2D arraythe_array = np.arange(50).reshape((5, 10))# row manipulationnp.random.shuffle(the_array)# display random rowsrows = the_array[:2, :]print(rows)
OutPut
[[10 11 12 13 14 15 16 17 18 19][ 0 1 2 3 4 5 6 7 8 9]]
Example 2
import randomimport numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))# row manipulationrows_id = random.sample(range(0, the_array.shape[1] - 1), 2)# display random rowsrows = the_array[rows_id, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
Example 3
import numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))number_of_rows = the_array.shape[0]random_indices = np.random.choice(number_of_rows,size=2,replace=False)# display random rowsrows = the_array[random_indices, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
以给定的精度漂亮地打印一个 Numpy 数组
Example 1
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)print(np.array_str(x, precision=1, suppress_small=True))
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[1.1 0.9 0. ][1.1 0.9 0. ][1.1 0.9 0. ]]
Example 2
import numpy as npx = np.random.random(10)print(x)np.set_printoptions(precision=3)print(x)
OutPut
[0.53828153 0.75848226 0.50046312 0.94723558 0.50415632 0.138996630.80301141 0.40887872 0.24837485 0.83008548][0.538 0.758 0.5 0.947 0.504 0.139 0.803 0.409 0.248 0.83 ]
Example 3
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)np.set_printoptions(suppress=True)print(x)
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[1.1 0.9 0.000001][1.1 0.9 0.000001][1.1 0.9 0.000001]]
Example 4
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)np.set_printoptions(formatter={'float': '{: 0.3f}'.format})print(x)
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[ 1.100 0.900 0.000][ 1.100 0.900 0.000][ 1.100 0.900 0.000]]
Example 5
import numpy as npx = np.random.random((3, 3)) * 9print(np.array2string(x, formatter={'float_kind': '{0:.3f}'.format}))
OutPut
[[3.479 1.490 5.674][6.043 7.025 1.597][0.261 8.530 2.298]]
提取 Numpy 矩阵的前 n 列
列范围1
import numpy as npthe_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],[4, 5, 6, 7, 5, 3, 2, 5],[8, 9, 10, 11, 4, 5, 3, 5]])print(the_arr[:, 1:5])
OutPut
[[ 1 2 3 5][ 5 6 7 5][ 9 10 11 4]]
列范围2
import numpy as npthe_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],[4, 5, 6, 7, 5, 3, 2, 5],[8, 9, 10, 11, 4, 5, 3, 5]])print(the_arr[:, np.r_[0:1, 5]])
OutPut
[[ 0 2 3 5][ 4 6 7 5][ 8 10 11 4]]
列范围3
import numpy as npthe_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],[4, 5, 6, 7, 5, 3, 2, 5],[8, 9, 10, 11, 4, 5, 3, 5]])print(the_arr[:, np.r_[:1, 3, 7:8]])
OutPut
[[ 0 3 8][ 4 7 5][ 8 11 5]]
特定列
import numpy as npthe_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],[4, 5, 6, 7, 5, 3, 2, 5],[8, 9, 10, 11, 4, 5, 3, 5]])print(the_arr[:, 1])
OutPut
[1 5 9]
特定行和列
import numpy as npthe_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],[4, 5, 6, 7, 5, 3, 2, 5],[8, 9, 10, 11, 4, 5, 3, 5]])print(the_arr[0:2, 1:3])
OutPut
[[1 2][5 6]]
从 NumPy 数组中删除值
Example 1
import numpy as npthe_array = np.array([[1, 2], [3, 4]])print(the_array)the_array = np.delete(the_array, [1, 2])print(the_array)
OutPut
[[1 2][3 4]][1 4]
Example 2
import numpy as npthe_array = np.array([1, 2, 3, 4])print(the_array)the_array = np.delete(the_array, np.where(the_array == 2))print(the_array)
OutPut
[1 2 3 4][1 3 4]
Example 3
import numpy as npthe_array = np.array([[1, 2], [3, 4]])print(the_array)the_array = np.delete(the_array, np.where(the_array == 3))print(the_array)
OutPut
[[1 2][3 4]][3 4]
将满足条件的项目替换为 Numpy 数组中的另一个值
将所有大于 30 的元素替换为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 30, 0, the_array)print(an_array)
OutPut
[ 0 7 0 27 13 0 0]
将大于 30 小于 50 的所有元素替换为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where((the_array > 30) & (the_array < 50), 0, the_array)print(an_array)
OutPut
[ 0 7 0 27 13 0 71]
给所有大于 40 的元素加 5
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 40, the_array + 5, the_array)print(an_array)
OutPut
[54 7 49 27 13 35 76]
用 Nan 替换数组中大于 25 的所有元素
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.where(the_array > 25, np.NaN, the_array)print(an_array)
OutPut
[nan 7. nan nan 13. nan nan]
将数组中大于 25 的所有元素替换为 1,否则为 0
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])an_array = np.asarray([0 if val < 25 else 1 for val in the_array])print(an_array)
OutPut
[1 0 1 1 0 1 1]
如何根据 Pandas 列中的值从 DataFrame 中选择或过滤行
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)column_sums = newarr[:, :].sum()print(column_sums)
OutPut
78
创建 3D NumPy 零数组
import numpy as npthe_3d_array = np.zeros((2, 2, 2))print(the_3d_array)
OutPut
[[[0. 0.][0. 0.]][[0. 0.][0. 0.]]]
计算 NumPy 数组中每一行的总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr.sum(axis=1)print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]][ 6 15 24 33]
打印没有科学记数法的 NumPy 数组
import numpy as npnp.set_printoptions(suppress=True,formatter={'float_kind': '{:f}'.format})the_array = np.array([3.74, 5162, 13683628846.64, 12783387559.86, 1.81])print(the_array)
OutPut
[3.740000 5162.000000 13683628846.639999 12783387559.860001 1.810000]
获取numpy数组中所有NaN值的索引列表
import numpy as npthe_array = np.array([np.nan, 2, 3, 4])array_has_nan = np.isnan(the_array)print(array_has_nan)
OutPut
[ True False False False]
检查 NumPy 数组中的所有元素都是 NaN
import numpy as npthe_array = np.array([np.nan, 2, 3, 4])array_has_nan = np.isnan(the_array).all()print(array_has_nan)the_array = np.array([np.nan, np.nan, np.nan, np.nan])array_has_nan = np.isnan(the_array).all()print(array_has_nan)
OutPut
FalseTrue
将列表添加到 Python 中的 NumPy 数组
import numpy as npthe_array = np.array([[1, 2], [3, 4]])columns_to_append = [5, 6]the_array = np.insert(the_array, 2, columns_to_append, axis=1)print(the_array)
OutPut
[[1 2 5][3 4 6]]
在 Numpy 中抑制科学记数法
import numpy as npnp.set_printoptions(suppress=True,formatter={'float_kind': '{:f}'.format})the_array = np.array([3.74, 5162, 13683628846.64, 12783387559.86, 1.81])print(the_array)
OutPut
[3.740000 5162.000000 13683628846.639999 12783387559.860001 1.810000]
将具有 12 个元素的一维数组转换为 3 维数组
Example 1
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(2, 3, 2)print(newarr)
OutPut
[[[ 1 2][ 3 4][ 5 6]][[ 7 8][ 9 10][11 12]]]
Example 2
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(3, 2, 2)print(newarr)
OutPut
[[[ 1 2][ 3 4]][[ 5 6][ 7 8]][[ 9 10][11 12]]]
Example 3
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(3, 2, 2).transpose()print(newarr)
OutPut
[[[ 1 5 9][ 3 7 11]][[ 2 6 10][ 4 8 12]]][[[ 1 2][ 3 4]][[ 5 6][ 7 8]][[ 9 10][11 12]]]
Example 4
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(-1, 2).T.reshape(-1, 3, 4)print(newarr)
OutPut
[[[ 1 3 5 7][ 9 11 2 4][ 6 8 10 12]]]
检查 NumPy 数组是否为空
import numpy as npthe_array = np.array([])is_empty = the_array.size == 0print(is_empty)the_array = np.array([1, 2, 3])is_empty = the_array.size == 0print(is_empty)
OutPut
TrueFalse
在 Python 中重塑 3D 数组
Example 1
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(2, 3, 2)print(newarr)
OutPut
[[[ 1 2][ 3 4][ 5 6]][[ 7 8][ 9 10][11 12]]]
Example 2
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(3, 2, 2)print(newarr)
OutPut
[[[ 1 2][ 3 4]][[ 5 6][ 7 8]][[ 9 10][11 12]]]
Example 3
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(3, 2, 2).transpose()print(newarr)
OutPut
[[[ 1 5 9][ 3 7 11]][[ 2 6 10][ 4 8 12]]]
Example 4
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(-1, 2).T.reshape(-1, 3, 4)print(newarr)
OutPut
[[[ 1 3 5 7][ 9 11 2 4][ 6 8 10 12]]]
在 Python 中重复 NumPy 数组中的一列
import numpy as npthe_array = np.array([1, 2, 3])repeat = 3new_array = np.transpose([the_array] * repeat)print(new_array)
OutPut
[[1 1 1][2 2 2][3 3 3]]
在 NumPy 数组中找到跨维度的平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array.mean(axis=0)print(mean_array)
OutPut
[3. 4. 5. 6.]
检查 NumPy 数组中的 NaN 元素
import numpy as npthe_array = np.array([np.nan, 2, 3, 4])array_has_nan = np.isnan(the_array).any()print(array_has_nan)the_array = np.array([1, 2, 3, 4])array_has_nan = np.isnan(the_array).any()print(array_has_nan)
OutPut
TrueFalse
格式化 NumPy 数组的打印方式
Example 1
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)print(np.array_str(x, precision=1, suppress_small=True))
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[1.1 0.9 0. ][1.1 0.9 0. ][1.1 0.9 0. ]]
Example 2
import numpy as npx = np.random.random(10)print(x)np.set_printoptions(precision=3)print(x)
OutPut
[0.53828153 0.75848226 0.50046312 0.94723558 0.50415632 0.138996630.80301141 0.40887872 0.24837485 0.83008548][0.538 0.758 0.5 0.947 0.504 0.139 0.803 0.409 0.248 0.83 ]
Example 3
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)np.set_printoptions(suppress=True)print(x)
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[1.1 0.9 0.000001][1.1 0.9 0.000001][1.1 0.9 0.000001]]
Example 4
import numpy as npx = np.array([[1.1, 0.9, 1e-6]] * 3)print(x)np.set_printoptions(formatter={'float': '{: 0.3f}'.format})print(x)
OutPut
[[1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06][1.1e+00 9.0e-01 1.0e-06]][[ 1.100 0.900 0.000][ 1.100 0.900 0.000][ 1.100 0.900 0.000]]
Example 5
import numpy as npx = np.random.random((3, 3)) * 9print(np.array2string(x, formatter={'float_kind': '{0:.3f}'.format}))
OutPut
[[3.479 1.490 5.674][6.043 7.025 1.597][0.261 8.530 2.298]]
乘以Numpy数组的每个元素
Example 1
import numpy as npthe_array = np.array([[1, 2, 3], [1, 2, 3]])prod = np.prod(the_array)print(prod)
OutPut
36
Example 2
import numpy as npthe_array = np.array([[1, 2, 3], [1, 2, 3]])prod = np.prod(the_array, 0)print(prod)
OutPut
[1 4 9]
Example 3
import numpy as npthe_array = np.array([[1, 2, 3], [1, 2, 3]])prod = np.prod(the_array, 1)print(prod)
OutPut
[6, 6]
Example 4
import numpy as npthe_array = np.array([1, 2, 3])prod = np.prod(the_array)print(prod)
OutPut
6
在 NumPy 中生成随机数
Example 1
import numpy as np# create 2D arraythe_array = np.arange(50).reshape((5, 10))# row manipulationnp.random.shuffle(the_array)# display random rowsrows = the_array[:2, :]print(rows)
OutPut
[[10 11 12 13 14 15 16 17 18 19][ 0 1 2 3 4 5 6 7 8 9]]
Example 2
import randomimport numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))# row manipulationrows_id = random.sample(range(0, the_array.shape[1] - 1), 2)# display random rowsrows = the_array[rows_id, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
Example 3
import numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))number_of_rows = the_array.shape[0]random_indices = np.random.choice(number_of_rows,size=2,replace=False)# display random rowsrows = the_array[random_indices, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
Numpy 将具有 8 个元素的一维数组转换为 Python 中的二维数组
4 行 2 列
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = arr.reshape(4, 2)print(newarr)
OutPut
[[1 2][3 4][5 6][7 8]]
2 行 4 列
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = arr.reshape(2, 4)print(newarr)
OutPut
[[1 2 3 4][5 6 7 8]]
在 Python 中使用 numpy.all()
import numpy as npthelist = [[True, True], [True, True]]thebool = np.all(thelist)print(thebool)thelist = [[False, False], [False, False]]thebool = np.all(thelist)print(thebool)thelist = [[True, False], [True, False]]thebool = np.all(thelist)print(thebool)
OutPut
True
将一维数组转换为二维数组
4 行 2 列
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = arr.reshape(4, 2)print(newarr)
OutPut
[[1 2][3 4][5 6][7 8]]
2 行 4 列
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = arr.reshape(2, 4)print(newarr)
OutPut
[[1 2 3 4][5 6 7 8]]
Example 3
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = np.reshape(arr, (-1, 2))print(newarr)
OutPut
[[1 2][3 4][5 6][7 8]]
通过添加新轴将一维数组转换为二维数组
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = np.reshape(arr, (1, arr.size))print(newarr)
OutPut
[[1 2 3 4 5 6 7 8]]
一维数组转为指定元素长度的二维数组
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = np.reshape(arr, (-1, 4))print(newarr)
OutPut
[[1 2 3 4][5 6 7 8]]
计算 NumPy 数组中唯一值的频率
import numpy as npthe_array = np.array([9, 7, 4, 7, 3, 5, 9])frequencies = np.asarray((np.unique(the_array, return_counts=True))).Tprint(frequencies)
OutPut
[[3 1][4 1][5 1][7 2][9 2]]
在一列中找到平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array.mean(axis=0)print(mean_array)
OutPut
[3. 4. 5. 6.]
在 Numpy 数组的长度、维度、大小
Example 1
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])print(arr.ndim)print(arr.shape)arr = np.array([[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]])print(arr.ndim)print(arr.shape)arr = np.array([[[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]]])print(arr.ndim)print(arr.shape)
OutPut
1(12,)2(3, 4)3(1, 3, 4)
Example 2
import numpy as nparr = np.array([[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]])print(np.info(arr))
OutPut
class: ndarrayshape: (3, 4)strides: (16, 4)itemsize: 4aligned: Truecontiguous: Truefortran: Falsedata pointer: 0x25da9fd5710byteorder: littlebyteswap: Falsetype: int32None
在 NumPy 数组中找到最大值的索引
import numpy as npthe_array = np.array([11, 22, 53, 14, 15])max_index_col = np.argmax(the_array, axis=0)print(max_index_col)
OutPut
2
按降序对 NumPy 数组进行排序
按降序对 Numpy 进行排序
import numpy as npthe_array = np.array([49, 7, 44, 27, 13, 35, 71])sort_array = np.sort(the_array)[::-1]print(sort_array)
OutPut
[71 49 44 35 27 13 7]
按降序对 2D Numpy 进行排序
import numpy as npthe_array = np.array([[49, 7, 4], [27, 13, 35]])sort_array = np.sort(the_array)[::1]print(sort_array)
OutPut
[[ 4 7 49][13 27 35]]
按降序对 Numpy 进行排序
import numpy as npthe_array = np.array([[49, 7, 4], [27, 13, 35], [12, 3, 5]])a_idx = np.argsort(-the_array)sort_array = np.take_along_axis(the_array, a_idx, axis=1)print(sort_array)
OutPut
[[49 7 4][35 27 13][12 5 3]]
Numpy 从二维数组中获取随机的一组行
Example 1
import numpy as np# create 2D arraythe_array = np.arange(50).reshape((5, 10))# row manipulationnp.random.shuffle(the_array)# display random rowsrows = the_array[:2, :]print(rows)
OutPut
[[10 11 12 13 14 15 16 17 18 19][ 0 1 2 3 4 5 6 7 8 9]]
Example 2
import randomimport numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))# row manipulationrows_id = random.sample(range(0, the_array.shape[1] - 1), 2)# display random rowsrows = the_array[rows_id, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
Example 3
import numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))number_of_rows = the_array.shape[0]random_indices = np.random.choice(number_of_rows,size=2,replace=False)# display random rowsrows = the_array[random_indices, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
将 Numpy 数组转换为 JSON
import numpy as npthe_array = np.array([[49, 7, 44], [27, 13, 35], [27, 13, 35]])lists = the_array.tolist()print([{'x': x[0], 'y': x[1], 'z': x[2]} for i, x in enumerate(lists)])
OutPut
[{'x': 49, 'y': 7, 'z': 44}, {'x': 27, 'y': 13, 'z': 35}, {'x': 27, 'y': 13, 'z': 35}]
检查 NumPy 数组中是否存在值
import numpy as npthe_array = np.array([[1, 2], [3, 4]])n = 3if n in the_array:print(True)else:print(False)
OutPut
TrueFalse
创建一个 3D NumPy 数组
import numpy as npthe_3d_array = np.ones((2, 2, 2))print(the_3d_array)
OutPut
[[[1. 1.][1. 1.]][[1. 1.][1. 1.]]]
在numpy中将字符串数组转换为浮点数数组
import numpy as npstring_arr = np.array(['1.1', '2.2', '3.3'])float_arr = string_arr.astype(np.float64)print(float_arr)
OutPut
[1.1 2.2 3.3]
从 Python 的 numpy 数组中随机选择
Example 1
import numpy as np# create 2D arraythe_array = np.arange(50).reshape((5, 10))# row manipulationnp.random.shuffle(the_array)# display random rowsrows = the_array[:2, :]print(rows)
OutPut
[[10 11 12 13 14 15 16 17 18 19][ 0 1 2 3 4 5 6 7 8 9]]
Example 2
import randomimport numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))# row manipulationrows_id = random.sample(range(0, the_array.shape[1] - 1), 2)# display random rowsrows = the_array[rows_id, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
Example 3
import numpy as np# create 2D arraythe_array = np.arange(16).reshape((4, 4))number_of_rows = the_array.shape[0]random_indices = np.random.choice(number_of_rows,size=2,replace=False)# display random rowsrows = the_array[random_indices, :]print(rows)
OutPut
[[ 4 5 6 7][ 8 9 10 11]]
不截断地打印完整的 NumPy 数组
import numpy as npnp.set_printoptions(threshold=np.inf)the_array = np.arange(100)print(the_array)
OutPut
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2324 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 4748 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7172 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 9596 97 98 99]
将 Numpy 转换为列表
import numpy as npthe_array = np.array([[1, 2], [3, 4]])print(the_array.tolist())
OutPut
[[1, 2], [3, 4]]
将字符串数组转换为浮点数数组
import numpy as npstring_arr = np.array(['1.1', '2.2', '3.3'])float_arr = string_arr.astype(np.float64)print(float_arr)
OutPut
[1.1 2.2 3.3]
计算 NumPy 数组中每一列的总和
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])newarr = arr.reshape(4, 3)print(newarr)column_sums = newarr.sum(axis=0)print(column_sums)
OutPut
[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]][22 26 30]
使用 Python 中的值创建 3D NumPy 数组
import numpy as npthe_3d_array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])print(the_3d_array)
OutPut
[[[1 2][3 4]][[5 6][7 8]]]
计算不同长度的 Numpy 数组的平均值
import numpy as npx = np.array([[1, 2], [3, 4]])y = np.array([[1, 2, 3], [3, 4, 5]])z = np.array([[7], [8]])arr = np.ma.empty((2, 3, 3))arr.mask = Truearr[:x.shape[0], :x.shape[1], 0] = xarr[:y.shape[0], :y.shape[1], 1] = yarr[:z.shape[0], :z.shape[1], 2] = zprint(arr.mean(axis=2))
OutPut
[[3.0 2.0 3.0][4.666666666666667 4.0 5.0]]
从 Numpy 数组中删除 nan 值
Example 1
import numpy as npx = np.array([np.nan, 2, 3, 4])x = x[~np.isnan(x)]print(x)
OutPut
[2. 3. 4.]
Example 2
import numpy as npx = np.array([[5, np.nan],[np.nan, 0],[1, 2],[3, 4]])x = x[~np.isnan(x).any(axis=1)]print(x)
OutPut
[[1. 2.][3. 4.]]
向 NumPy 数组添加一列
import numpy as npthe_array = np.array([[1, 2], [3, 4]])columns_to_append = np.array([[5], [6]])the_array = np.append(the_array, columns_to_append, 1)print(the_array)
OutPut
[[1 2 5][3 4 6]]
在 Numpy Array 中打印浮点值时如何抑制科学记数法
import numpy as npnp.set_printoptions(suppress=True,formatter={'float_kind': '{:f}'.format})the_array = np.array([3.74, 5162, 13683628846.64, 12783387559.86, 1.81])print(the_array)
OutPut
[3.740000 5162.000000 13683628846.639999 12783387559.860001 1.810000]
Numpy 将 1d 数组重塑为 1 列的 2d 数组
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8])newarr = arr.reshape(arr.shape[0], -1)print(newarr)
OutPut
[[1][2][3][4][5][6][7][8]]
初始化 NumPy 数组
import numpy as npthearray = np.array([[1, 2], [3, 4], [5, 6]])print(thearray)
OutPut
[[1 2][3 4][5 6]]
创建重复一行
import numpy as npthe_array = np.array([1, 2, 3])repeat = 3new_array = np.tile(the_array, (repeat, 1))print(new_array)
OutPut
[[1 2 3][1 2 3][1 2 3]]
将 NumPy 数组附加到 Python 中的空数组
import numpy as npthe_array = np.array([1, 2, 3, 4])empty_array = np.array([])new_array = np.append(empty_array, the_array)print(new_array)
OutPut
[1. 2. 3. 4.]
找到 Numpy 数组的平均值
计算每列的平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array.mean(axis=0)print(mean_array)
OutPut
[3. 4. 5. 6.]
计算每一行的平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array.mean(axis=1)print(mean_array)
OutPut
[2.5 6.5]
仅第一列的平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array[:, 0].mean()print(mean_array)
OutPut
3.0
仅第二列的平均值
import numpy as npthe_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])mean_array = the_array[:, 0].mean()print(mean_array)
OutPut
4.0
检测 NumPy 数组是否包含至少一个非数字值
import numpy as npthe_array = np.array([np.nan, 2, 3, 4])array_has_nan = np.isnan(the_array).any()print(array_has_nan)the_array = np.array([1, 2, 3, 4])array_has_nan = np.isnan(the_array).any()print(array_has_nan)
OutPut
TrueFalse
在 Python 中附加 NumPy 数组
import numpy as npthe_array = np.array([[0, 1], [2, 3]])row_to_append = np.array([[4, 5]])the_array = np.append(the_array, row_to_append, 0)print(the_array)print('*' * 10)columns_to_append = np.array([[7], [8], [9]])the_array = np.append(the_array, columns_to_append, 1)print(the_array)
OutPut
[[0 1][2 3][4 5]]**********[[0 1 7][2 3 8][4 5 9]]
使用 numpy.any()
import numpy as npthearr = [[True, False], [True, True]]thebool = np.any(thearr)print(thebool)thearr = [[False, False], [False, False]]thebool = np.any(thearr)print(thebool)
OutPut
TrueFalse
获得 NumPy 数组的转置
import numpy as npthe_array = np.array([[1, 2], [3, 4]])print(the_array)print(the_array.T)
OutPut
[[1 2][3 4]][[1 3][2 4]]
获取和设置NumPy数组的数据类型
import numpy as nptype1 = np.array([1, 2, 3, 4, 5, 6])type2 = np.array([1.5, 2.5, 0.5, 6])type3 = np.array(['a', 'b', 'c'])type4 = np.array(["Canada", "Australia"], dtype='U5')type5 = np.array([555, 666], dtype=float)print(type1.dtype)print(type2.dtype)print(type3.dtype)print(type4.dtype)print(type5.dtype)print(type4)
OutPut
int32float64<U1<U5float64['Canad' 'Austr']
获得NumPy数组的形状
import numpy as nparray1d = np.array([1, 2, 3, 4, 5, 6])array2d = np.array([[1, 2, 3], [4, 5, 6]])array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])print(array1d.shape)print(array2d.shape)print(array3d.shape)
OutPut
(6,)(2, 3)(2, 2, 3)
获得 1、2 或 3 维 NumPy 数组
import numpy as nparray1d = np.array([1, 2, 3, 4, 5, 6])print(array1d.ndim) # 1array2d = np.array([[1, 2, 3], [4, 5, 6]])print(array2d.ndim) # 2array3d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])array3d = array3d.reshape(2, 3, 2)print(array3d.ndim) # 3
OutPut
123
重塑 NumPy 数组
import numpy as npthearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])thearray = thearray.reshape(2, 4)print(thearray)print("-" * 10)thearray = thearray.reshape(4, 2)print(thearray)print("-" * 10)thearray = thearray.reshape(8, 1)print(thearray)
OutPut
[[1 2 3 4][5 6 7 8]]----------[[1 2][3 4][5 6][7 8]]----------[[1][2][3][4][5][6][7][8]]
调整 NumPy 数组的大小
import numpy as npthearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])thearray.resize(4)print(thearray)print("-" * 10)thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])thearray.resize(2, 4)print(thearray)print("-" * 10)thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])thearray.resize(3, 3)print(thearray)
OutPut
[1 2 3 4]----------[[1 2 3 4][5 6 7 8]]----------[[1 2 3][4 5 6][7 8 0]]
将 List 或 Tuple 转换为 NumPy 数组
import numpy as npthelist = [1, 2, 3]print(type(thelist)) # <class 'list'>array1 = np.array(thelist)print(type(array1)) # <class 'numpy.ndarray'>thetuple = ((1, 2, 3))print(type(thetuple)) # <class 'tuple'>array2 = np.array(thetuple)print(type(array2)) # <class 'numpy.ndarray'>array3 = np.array([thetuple, thelist, array1])print(array3)
OutPut
<class 'list'><class 'numpy.ndarray'><class 'tuple'><class 'numpy.ndarray'>[[1 2 3][1 2 3][1 2 3]]
使用 arange 函数创建 NumPy 数组s
import numpy as nparray1d = np.arange(5) # 1 row and 5 columnsprint(array1d)array1d = np.arange(0, 12, 2) # 1 row and 6 columnsprint(array1d)array2d = np.arange(0, 12, 2).reshape(2, 3) # 2 rows 3 columnsprint(array2d)array3d = np.arange(9).reshape(3, 3) # 3 rows and columnsprint(array3d)
OutPut
[0 1 2 3 4][ 0 2 4 6 8 10][[ 0 2 4][ 6 8 10]][[0 1 2][3 4 5][6 7 8]]
使用 linspace() 创建 NumPy 数组
import numpy as nparray1d = np.linspace(1, 12, 2)print(array1d)array1d = np.linspace(1, 12, 4)print(array1d)array2d = np.linspace(1, 12, 12).reshape(4, 3)print(array2d)
OutPut
[ 1. 12.][ 1. 4.66666667 8.33333333 12. ][[ 1. 2. 3.][ 4. 5. 6.][ 7. 8. 9.][10. 11. 12.]]
NumPy 日志空间数组示例
import numpy as npthearray = np.logspace(5, 10, num=10, base=10000000.0, dtype=float)print(thearray)
OutPut
[1.00000000e+35 7.74263683e+38 5.99484250e+42 4.64158883e+463.59381366e+50 2.78255940e+54 2.15443469e+58 1.66810054e+621.29154967e+66 1.00000000e+70]
创建 Zeros NumPy 数组
import numpy as nparray1d = np.zeros(3)print(array1d)array2d = np.zeros((2, 4))print(array2d)
OutPut
[0. 0. 0.][[0. 0. 0. 0.][0. 0. 0. 0.]]
NumPy One 数组示例
import numpy as nparray1d = np.ones(3)print(array1d)array2d = np.ones((2, 4))print(array2d)
OutPut
[1. 1. 1.][[1. 1. 1. 1.][1. 1. 1. 1.]]
NumPy 完整数组示例
import numpy as nparray1d = np.full((3), 2)print(array1d)array2d = np.full((2, 4), 3)print(array2d)
OutPut
[2 2 2][[3 3 3 3][3 3 3 3]]
NumPy Eye 数组示例
import numpy as nparray1 = np.eye(3, dtype=int)print(array1)array2 = np.eye(5, k=2)print(array2)
OutPut
[[1 0 0][0 1 0][0 0 1]][[0. 0. 1. 0. 0.][0. 0. 0. 1. 0.][0. 0. 0. 0. 1.][0. 0. 0. 0. 0.][0. 0. 0. 0. 0.]]
NumPy 生成随机数数组
import numpy as npprint(np.random.rand(3, 2)) # Uniformly distributed values.print(np.random.randn(3, 2)) # Normally distributed values.# Uniformly distributed integers in a given range.print(np.random.randint(2, size=10))print(np.random.randint(5, size=(2, 4)))
OutPut
[[0.68428242 0.62467648][0.28595395 0.96066372][0.63394485 0.94036659]][[0.29458704 0.84015551][0.42001253 0.89660667][0.50442113 0.46681958]][0 1 1 0 0 0 0 1 0 0][[3 3 2 3][2 1 2 0]]
NumPy 标识和对角线数组示例
import numpy as npprint(np.identity(3))print(np.diag(np.arange(0, 8, 2)))print(np.diag(np.diag(np.arange(9).reshape((3,3)))))
OutPut
[[1. 0. 0.][0. 1. 0.][0. 0. 1.]][[0 0 0 0][0 2 0 0][0 0 4 0][0 0 0 6]][[0 0 0][0 4 0][0 0 8]]
NumPy 索引示例
import numpy as nparray1d = np.array([1, 2, 3, 4, 5, 6])print(array1d[0]) # Get first valueprint(array1d[-1]) # Get last valueprint(array1d[3]) # Get 4th value from firstprint(array1d[-5]) # Get 5th value from last# Get multiple valuesprint(array1d[[0, -1]])print("-" * 10)array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])print(array2d)print("-" * 10)print(array2d[0, 0]) # Get first row first colprint(array2d[0, 1]) # Get first row second colprint(array2d[0, 2]) # Get first row third colprint(array2d[0, 1]) # Get first row second colprint(array2d[1, 1]) # Get second row second colprint(array2d[2, 1]) # Get third row second col
OutPut
1642[1 6]----------[[1 2 3][4 5 6][7 8 9]]----------123258
多维数组中的 NumPy 索引
import numpy as nparray3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])print(array3d)print(array3d[0, 0, 0])print(array3d[0, 0, 1])print(array3d[0, 0, 2])print(array3d[0, 1, 0])print(array3d[0, 1, 1])print(array3d[0, 1, 2])print(array3d[1, 0, 0])print(array3d[1, 0, 1])print(array3d[1, 0, 2])print(array3d[1, 1, 0])print(array3d[1, 1, 1])print(array3d[1, 1, 2])
OutPut
[[[ 1 2 3][ 4 5 6]][[ 7 8 9][10 11 12]]]123456789101112
NumPy 单维切片示例
import numpy as nparray1d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])print(array1d[4:]) # From index 4 to last indexprint(array1d[:4]) # From index 0 to 4 indexprint(array1d[4:7]) # From index 4(included) up to index 7(excluded)print(array1d[:-1]) # Excluded last elementprint(array1d[:-2]) # Up to second last index(negative index)print(array1d[::-1]) # From last to first in reverse order(negative step)print(array1d[::-2]) # All odd numbers in reversed orderprint(array1d[-2::-2]) # All even numbers in reversed orderprint(array1d[::]) # All elements
OutPut
[4 5 6 7 8 9][0 1 2 3][4 5 6][0 1 2 3 4 5 6 7 8][0 1 2 3 4 5 6 7][9 8 7 6 5 4 3 2 1 0][9 7 5 3 1][8 6 4 2 0][0 1 2 3 4 5 6 7 8 9]
NumPy 数组中的多维切片
import numpy as nparray2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])print("-" * 10)print(array2d[:, 0:2]) # 2nd and 3rd colprint("-" * 10)print(array2d[1:3, 0:3]) # 2nd and 3rd rowprint("-" * 10)print(array2d[-1::-1, -1::-1]) # Reverse an array
OutPut
----------[[1 2][4 5][7 8]]----------[[4 5 6][7 8 9]]----------[[9 8 7][6 5 4][3 2 1]]
翻转 NumPy 数组的轴顺序
import numpy as nparray2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])print(array2d)print("-" * 10)# Permute the dimensions of an array.arrayT = np.transpose(array2d)print(arrayT)print("-" * 10)# Flip array in the left/right direction.arrayFlr = np.fliplr(array2d)print(arrayFlr)print("-" * 10)# Flip array in the up/down direction.arrayFud = np.flipud(array2d)print(arrayFud)print("-" * 10)# Rotate an array by 90 degrees in the plane specified by axes.arrayRot90 = np.rot90(array2d)print(arrayRot90)
OutPut
[[1 2 3][4 5 6][7 8 9]]----------[[1 4 7][2 5 8][3 6 9]]----------[[3 2 1][6 5 4][9 8 7]]----------[[7 8 9][4 5 6][1 2 3]]----------[[3 6 9][2 5 8][1 4 7]]
NumPy 数组的连接和堆叠
import numpy as nparray1 = np.array([[1, 2, 3], [4, 5, 6]])array2 = np.array([[7, 8, 9], [10, 11, 12]])# Stack arrays in sequence horizontally (column wise).arrayH = np.hstack((array1, array2))print(arrayH)print("-" * 10)# Stack arrays in sequence vertically (row wise).arrayV = np.vstack((array1, array2))print(arrayV)print("-" * 10)# Stack arrays in sequence depth wise (along third axis).arrayD = np.dstack((array1, array2))print(arrayD)print("-" * 10)# Appending arrays after each other, along a given axis.arrayC = np.concatenate((array1, array2))print(arrayC)print("-" * 10)# Append values to the end of an array.arrayA = np.append(array1, array2, axis=0)print(arrayA)print("-" * 10)arrayA = np.append(array1, array2, axis=1)print(arrayA)
OutPut
[[ 1 2 3 7 8 9][ 4 5 6 10 11 12]]----------[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]----------[[[ 1 7][ 2 8][ 3 9]][[ 4 10][ 5 11][ 6 12]]]----------[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]----------[[ 1 2 3][ 4 5 6][ 7 8 9][10 11 12]]----------[[ 1 2 3 7 8 9][ 4 5 6 10 11 12]]
NumPy 数组的算术运算
import numpy as nparray1 = np.array([[1, 2, 3], [4, 5, 6]])array2 = np.array([[7, 8, 9], [10, 11, 12]])print(array1 + array2)print("-" * 20)print(array1 - array2)print("-" * 20)print(array1 * array2)print("-" * 20)print(array2 / array1)print("-" * 40)print(array1 ** array2)print("-" * 40)
OutPut
[[ 8 10 12][14 16 18]]--------------------[[-6 -6 -6][-6 -6 -6]]--------------------[[ 7 16 27][40 55 72]]--------------------[[7. 4. 3. ][2.5 2.2 2. ]]----------------------------------------[[ 1 256 19683][ 1048576 48828125 -2118184960]]----------------------------------------
NumPy 数组上的标量算术运算
import numpy as nparray1 = np.array([[10, 20, 30], [40, 50, 60]])print(array1 + 2)print("-" * 20)print(array1 - 5)print("-" * 20)print(array1 * 2)print("-" * 20)print(array1 / 5)print("-" * 20)print(array1 ** 2)print("-" * 20)
OutPut
[[12 22 32][42 52 62]]--------------------[[ 5 15 25][35 45 55]]--------------------[[ 20 40 60][ 80 100 120]]--------------------[[ 2. 4. 6.][ 8. 10. 12.]]--------------------[[ 100 400 900][1600 2500 3600]]--------------------
NumPy 初等数学函数
import numpy as nparray1 = np.array([[10, 20, 30], [40, 50, 60]])print(np.sin(array1))print("-" * 40)print(np.cos(array1))print("-" * 40)print(np.tan(array1))print("-" * 40)print(np.sqrt(array1))print("-" * 40)print(np.exp(array1))print("-" * 40)print(np.log10(array1))print("-" * 40)
OutPut
[[-0.54402111 0.91294525 -0.98803162][ 0.74511316 -0.26237485 -0.30481062]]----------------------------------------[[-0.83907153 0.40808206 0.15425145][-0.66693806 0.96496603 -0.95241298]]----------------------------------------[[ 0.64836083 2.23716094 -6.4053312 ][-1.11721493 -0.27190061 0.32004039]]----------------------------------------[[3.16227766 4.47213595 5.47722558][6.32455532 7.07106781 7.74596669]]----------------------------------------[[2.20264658e+04 4.85165195e+08 1.06864746e+13][2.35385267e+17 5.18470553e+21 1.14200739e+26]]----------------------------------------[[1. 1.30103 1.47712125][1.60205999 1.69897 1.77815125]]----------------------------------------
NumPy Element Wise 数学运算
import numpy as nparray1 = np.array([[10, 20, 30], [40, 50, 60]])array2 = np.array([[2, 3, 4], [4, 6, 8]])array3 = np.array([[-2, 3.5, -4], [4.05, -6, 8]])print(np.add(array1, array2))print("-" * 40)print(np.power(array1, array2))print("-" * 40)print(np.remainder((array2), 5))print("-" * 40)print(np.reciprocal(array3))print("-" * 40)print(np.sign(array3))print("-" * 40)print(np.ceil(array3))print("-" * 40)print(np.round(array3))print("-" * 40)
OutPut
[[12 23 34][44 56 68]]----------------------------------------[[ 100 8000 810000][ 2560000 -1554869184 -1686044672]]----------------------------------------[[2 3 4][4 1 3]]----------------------------------------[[-0.5 0.28571429 -0.25 ][ 0.24691358 -0.16666667 0.125 ]]----------------------------------------[[-1. 1. -1.][ 1. -1. 1.]]----------------------------------------[[-2. 4. -4.][ 5. -6. 8.]]----------------------------------------[[-2. 4. -4.][ 4. -6. 8.]]----------------------------------------
NumPy 聚合和统计函数
import numpy as nparray1 = np.array([[10, 20, 30], [40, 50, 60]])print("Mean: ", np.mean(array1))print("Std: ", np.std(array1))print("Var: ", np.var(array1))print("Sum: ", np.sum(array1))print("Prod: ", np.prod(array1))
OutPut
Mean: 35.0Std: 17.07825127659933Var: 291.6666666666667Sum: 210Prod: 720000000
Where 函数的 NumPy 示例
import numpy as npbefore = np.array([[1, 2, 3], [4, 5, 6]])# If element is less than 4, mul by 2 else by 3after = np.where(before < 4, before * 2, before * 3)print(after)
OutPut
[[ 2 4 6][12 15 18]]
Select 函数的 NumPy 示例
import numpy as npbefore = np.array([[1, 2, 3], [4, 5, 6]])# If element is less than 4, mul by 2 else by 3after = np.select([before < 4, before], [before * 2, before * 3])print(after)
OutPut
[[ 2 4 6][12 15 18]]
选择函数的 NumPy 示例
import numpy as npbefore = np.array([[0, 1, 2], [2, 0, 1], [1, 2, 0]])choices = [5, 10, 15]after = np.choose(before, choices)print(after)print("-" * 10)before = np.array([[0, 0, 0], [2, 2, 2], [1, 1, 1]])choice1 = [5, 10, 15]choice2 = [8, 16, 24]choice3 = [9, 18, 27]after = np.choose(before, (choice1, choice2, choice3))print(after)
OutPut
[[ 5 10 15][15 5 10][10 15 5]]----------[[ 5 10 15][ 9 18 27][ 8 16 24]]
NumPy 逻辑操作,用于根据给定条件从数组中选择性地选取值
import numpy as npthearray = np.array([[10, 20, 30], [14, 24, 36]])print(np.logical_or(thearray < 10, thearray > 15))print("-" * 30)print(np.logical_and(thearray < 10, thearray > 15))print("-" * 30)print(np.logical_not(thearray < 20))print("-" * 30)
OutPut
[[False True True][False True True]]------------------------------[[False False False][False False False]]------------------------------[[False True True][False True True]]------------------------------
标准集合操作的 NumPy 示例
import numpy as nparray1 = np.array([[10, 20, 30], [14, 24, 36]])array2 = np.array([[20, 40, 50], [24, 34, 46]])# Find the union of two arrays.print(np.union1d(array1, array2))# Find the intersection of two arrays.print(np.intersect1d(array1, array2))# Find the set difference of two arrays.print(np.setdiff1d(array1, array2))
OutPut
[10 14 20 24 30 34 36 40 46 50][20 24][10 14 30 36]
