再肝3天,整理了90个NumPy案例,不能不收藏!(上)

简介: 再肝3天,整理了90个NumPy案例,不能不收藏!(上)

Numpy 是什么就不太过多介绍了,懂的人都懂!

文章很长,总是要忍一下,如果忍不了,那就收藏吧,总会用到的

萝卜哥也贴心的做成了PDF,在文末获取!


  • 有多个条件时替换 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 示例


1有多个条件时替换 Numpy 数组中的元素


将所有大于 30 的元素替换为 0

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)

Output:

[ 0  7  0 27 13  0  0]

将大于 30 小于 50 的所有元素替换为 0

import numpy as np
the_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 np
the_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 np
the_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 np
the_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]


2在 Python 中找到 Numpy 数组的维度


import numpy as np
arr = 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:

1
2
3


3两个条件过滤 NumPy 数组


Example 1

import numpy as np
the_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 np
the_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 np
the_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 np
the_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 np
the_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:

[]


4对最后一列求和


第一列总和

import numpy as np
arr = 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 np
arr = 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 np
arr = 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 np
arr = 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


5满足条件,则替换 Numpy 元素


将所有大于 30 的元素替换为 0

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)

Output:

[ 0  7  0 27 13  0  0]

将大于 30 小于 50 的所有元素替换为 0

import numpy as np
the_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 np
the_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 np
the_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 np
the_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]


6从 Nump y数组中随机选择两行


Example 1

import numpy as np
# create 2D array
the_array = np.arange(50).reshape((5, 10))
# row manipulation
np.random.shuffle(the_array)
# display random rows
rows = 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 random
import numpy as np
# create 2D array
the_array = np.arange(16).reshape((4, 4))
# row manipulation
rows_id = random.sample(range(0, the_array.shape[1] - 1), 2)
# display random rows
rows = the_array[rows_id, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]

Example 3

import numpy as np
# create 2D array
the_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 rows
rows = the_array[random_indices, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]


7以给定的精度漂亮地打印一个 Numpy 数组


Example 1

import numpy as np
x = 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 np
x = 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.13899663
 0.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 np
x = 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 np
x = 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 np
x = np.random.random((3, 3)) * 9
print(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]]


8提取 Numpy 矩阵的前 n 列


列范围1

import numpy as np
the_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 np
the_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 np
the_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 np
the_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 np
the_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]]


9从 NumPy 数组中删除值


Example 1

import numpy as np
the_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 np
the_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 np
the_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]


10将满足条件的项目替换为 Numpy 数组中的另一个值


将所有大于 30 的元素替换为 0

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)

Output:

[ 0  7  0 27 13  0  0]

将大于 30 小于 50 的所有元素替换为 0

import numpy as np
the_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 np
the_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 np
the_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 np
the_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]


11对 NumPy 数组中的所有元素求和


import numpy as np
arr = 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


12创建 3D NumPy 零数组


import numpy as np
the_3d_array = np.zeros((2, 2, 2))
print(the_3d_array)

Output:

[[[0. 0.]
  [0. 0.]]
 [[0. 0.]
  [0. 0.]]]


13计算 NumPy 数组中每一行的总和


import numpy as np
arr = 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]


14打印没有科学记数法的 NumPy 数组


import numpy as np
np.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]


15获取numpy数组中所有NaN值的索引列表


import numpy as np
the_array = np.array([np.nan, 2, 3, 4])
array_has_nan = np.isnan(the_array)
print(array_has_nan)

Output:

[ True False False False]


16检查 NumPy 数组中的所有元素都是 NaN


import numpy as np
the_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:

False
True


17将列表添加到 Python 中的 NumPy 数组


import numpy as np
the_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]]


18在 Numpy 中抑制科学记数法


import numpy as np
np.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]


19将具有 12 个元素的一维数组转换为 3 维数组


Example 1

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)

Output:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)

Example 2

import numpy as np
arr = 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 np
arr = 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 np
arr = 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]]]


20检查 NumPy 数组是否为空


import numpy as np
the_array = np.array([])
is_empty = the_array.size == 0
print(is_empty)
the_array = np.array([1, 2, 3])
is_empty = the_array.size == 0
print(is_empty)

Output:

True
False


21在 Python 中重塑 3D 数组


Example 1

import numpy as np
arr = 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 np
arr = 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 np
arr = 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 np
arr = 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]]]


22在 Python 中重复 NumPy 数组中的一列


import numpy as np
the_array = np.array([1, 2, 3])
repeat = 3
new_array = np.transpose([the_array] * repeat)
print(new_array)

Output:

[[1 1 1]
 [2 2 2]
 [3 3 3]]


23在 NumPy 数组中找到跨维度的平均值


import numpy as np
the_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.]


24检查 NumPy 数组中的 NaN 元素


import numpy as np
the_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:

True
False


25格式化 NumPy 数组的打印方式


Example 1

import numpy as np
x = 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 np
x = 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.13899663
 0.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 np
x = 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 np
x = 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 np
x = np.random.random((3, 3)) * 9
print(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]]


26乘以Numpy数组的每个元素


Example 1

import numpy as np
the_array = np.array([[1, 2, 3], [1, 2, 3]])
prod = np.prod(the_array)
print(prod)

Output:

36

Example 2

import numpy as np
the_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 np
the_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 np
the_array = np.array([1, 2, 3])
prod = np.prod(the_array)
print(prod)

Output:

6


27在 NumPy 中生成随机数


Example 1

import numpy as np
# create 2D array
the_array = np.arange(50).reshape((5, 10))
# row manipulation
np.random.shuffle(the_array)
# display random rows
rows = 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 random
import numpy as np
# create 2D array
the_array = np.arange(16).reshape((4, 4))
# row manipulation
rows_id = random.sample(range(0, the_array.shape[1] - 1), 2)
# display random rows
rows = the_array[rows_id, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]

Example 3

import numpy as np
# create 2D array
the_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 rows
rows = the_array[random_indices, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]


28Numpy 将具有 8 个元素的一维数组转换为 Python 中的二维数组


4 行 2 列

import numpy as np
arr = 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 np
arr = 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]]


29在 Python 中使用 numpy.all()


import numpy as np
thelist = [[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


30将一维数组转换为二维数组


4 行 2 列

import numpy as np
arr = 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 np
arr = 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 np
arr = 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 np
arr = 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]]

Example 5

import numpy as np
arr = 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]]


31计算 NumPy 数组中唯一值的频率


import numpy as np
the_array = np.array([9, 7, 4, 7, 3, 5, 9])
frequencies = np.asarray((np.unique(the_array, return_counts=True))).T
print(frequencies)

Output:

[[3 1]
 [4 1]
 [5 1]
 [7 2]
 [9 2]]


32在一列中找到平均值


import numpy as np
the_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.]


33在 Numpy 数组的长度、维度、大小


Example 1

import numpy as np
arr = 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 np
arr = np.array([[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]])
print(np.info(arr))

Output:

class:  ndarray
shape:  (3, 4)
strides:  (16, 4)
itemsize:  4
aligned:  True
contiguous:  True
fortran:  False
data pointer: 0x25da9fd5710
byteorder:  little
byteswap:  False
type: int32
None


34在 NumPy 数组中找到最大值的索引


import numpy as np
the_array = np.array([11, 22, 53, 14, 15])
max_index_col = np.argmax(the_array, axis=0)
print(max_index_col)

Output:

2


35按降序对 NumPy 数组进行排序


按降序对 Numpy 进行排序

import numpy as np
the_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 np
the_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 np
the_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]]


36Numpy 从二维数组中获取随机的一组行


Example 1

import numpy as np
# create 2D array
the_array = np.arange(50).reshape((5, 10))
# row manipulation
np.random.shuffle(the_array)
# display random rows
rows = 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 random
import numpy as np
# create 2D array
the_array = np.arange(16).reshape((4, 4))
# row manipulation
rows_id = random.sample(range(0, the_array.shape[1] - 1), 2)
# display random rows
rows = the_array[rows_id, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]

Example 3

import numpy as np
# create 2D array
the_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 rows
rows = the_array[random_indices, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]


37将 Numpy 数组转换为 JSON


import numpy as np
the_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}]


38检查 NumPy 数组中是否存在值


import numpy as np
the_array = np.array([[1, 2], [3, 4]])
n = 3
if n in the_array:
    print(True)
else:
    print(False)

Output:

True
False


39创建一个 3D NumPy 数组


import numpy as np
the_3d_array = np.ones((2, 2, 2))
print(the_3d_array)

Output:

[[[1. 1.]
  [1. 1.]]
 [[1. 1.]
  [1. 1.]]]


40在numpy中将字符串数组转换为浮点数数组


import numpy as np
string_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]


41从 Python 的 numpy 数组中随机选择


Example 1

import numpy as np
# create 2D array
the_array = np.arange(50).reshape((5, 10))
# row manipulation
np.random.shuffle(the_array)
# display random rows
rows = 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 random
import numpy as np
# create 2D array
the_array = np.arange(16).reshape((4, 4))
# row manipulation
rows_id = random.sample(range(0, the_array.shape[1] - 1), 2)
# display random rows
rows = the_array[rows_id, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]

Example 3

import numpy as np
# create 2D array
the_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 rows
rows = the_array[random_indices, :]
print(rows)

Output:

[[ 4  5  6  7]
 [ 8  9 10 11]]


42不截断地打印完整的 NumPy 数组


import numpy as np
np.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 23
 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 96 97 98 99]


43将 Numpy 转换为列表


import numpy as np
the_array = np.array([[1, 2], [3, 4]])
print(the_array.tolist())

Output:

[[1, 2], [3, 4]]


44将字符串数组转换为浮点数数组


import numpy as np
string_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]


45计算 NumPy 数组中每一列的总和


import numpy as np
arr = 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]
相关文章
|
4月前
|
机器学习/深度学习 算法 数据挖掘
使用NumPy实现经典算法案例集
【4月更文挑战第17天】本文展示了NumPy在Python中实现经典算法的案例,包括使用NumPy进行冒泡排序、计算欧几里得距离、矩阵转置和协方差矩阵。这些示例突显了NumPy在数值计算、数据分析和科学计算中的威力,强调了掌握NumPy对于数据科学家和机器学习开发者的重要性。
|
4月前
|
JSON 数据格式 索引
再肝3天,整理了90个NumPy案例,不能不收藏!
再肝3天,整理了90个NumPy案例,不能不收藏!
236 0
|
数据挖掘 Python
使用Python和NumPy进行数据分析的实际案例
使用Python和NumPy进行数据分析的实际案例
|
机器学习/深度学习 数据采集 数据建模
Python机器学习数据建模与分析——Numpy和Pandas综合应用案例:空气质量监测数据的预处理和基本分析
本篇文章主要以北京市空气质量监测数据为例子,聚集数据建模中的数据预处理和基本分析环节,说明Numpy和Pandas的数据读取、数据分组、数据重编码、分类汇总等数据加工处理功能。同时在实现案例的过程中对用到的Numpy和Pandas相关函数进行讲解。
638 0
Python机器学习数据建模与分析——Numpy和Pandas综合应用案例:空气质量监测数据的预处理和基本分析
|
数据挖掘 索引 Python
【Python数据分析 - 7】:Numpy中的统计运算(股票小案例)
【Python数据分析 - 7】:Numpy中的统计运算(股票小案例)
141 0
【Python数据分析 - 7】:Numpy中的统计运算(股票小案例)
|
数据采集 数据可视化 Python
Python案例教学之数据可视化,panda,numpy,Matplotlib库【第十课】
利用Matplotlib库,绘制出抛物线曲线图 1.线为红色圆型点线图 2.横坐标取值范围:[-10, 10],绘制点数50 3.坐标轴说明(x轴:x tick,y軕:voltage) 4.图标题为抛物线示意图。
296 1
Python案例教学之数据可视化,panda,numpy,Matplotlib库【第十课】
|
索引 Python
再肝3天,整理了90个NumPy案例,不能不收藏!(下)
再肝3天,整理了90个NumPy案例,不能不收藏!(下)
|
1月前
|
机器学习/深度学习 数据处理 计算机视觉
NumPy实践宝典:Python高手教你如何轻松玩转数据处理!
【8月更文挑战第22天】NumPy是Python科学计算的核心库,专长于大型数组与矩阵运算,并提供了丰富的数学函数。首先需安装NumPy (`pip install numpy`)。之后可通过创建数组、索引与切片、执行数学与逻辑运算、变换数组形状及类型、计算统计量和进行矩阵运算等操作来实践学习。NumPy的应用范围广泛,从基础的数据处理到图像处理都能胜任,是数据科学领域的必备工具。
45 0
|
2天前
|
机器学习/深度学习 算法 数据可视化
8种数值变量的特征工程技术:利用Sklearn、Numpy和Python将数值转化为预测模型的有效特征
特征工程是机器学习流程中的关键步骤,通过将原始数据转换为更具意义的特征,增强模型对数据关系的理解能力。本文重点介绍处理数值变量的高级特征工程技术,包括归一化、多项式特征、FunctionTransformer、KBinsDiscretizer、对数变换、PowerTransformer、QuantileTransformer和PCA,旨在提升模型性能。这些技术能够揭示数据中的潜在模式、优化变量表示,并应对数据分布和内在特性带来的挑战,从而提高模型的稳健性和泛化能力。每种技术都有其独特优势,适用于不同类型的数据和问题。通过实验和验证选择最适合的变换方法至关重要。
13 5
8种数值变量的特征工程技术:利用Sklearn、Numpy和Python将数值转化为预测模型的有效特征
|
29天前
|
机器学习/深度学习 存储 算法
NumPy 与 SciPy:Python 科学计算库的比较
【8月更文挑战第30天】
71 5