再肝3天,整理了90个 NumPy 例子,不能不收藏!

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情

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

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

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

[TOC]

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


在 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

两个条件过滤 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:

[]

对最后一列求和

第一列总和

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

满足条件,则替换 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]


从 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]]







以给定的精度漂亮地打印一个 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]]

提取 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]]

从 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]

将满足条件的项目替换为 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]


对 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

创建 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.]]]

计算 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]

打印没有科学记数法的 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]


获取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]

检查 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

将列表添加到 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]]

在 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]


将具有 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]]]

检查 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




在 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]]]

在 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]]

在 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.]


检查 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




格式化 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]]

乘以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

在 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]]







Numpy 将具有 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]]


在 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





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

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]]


计算 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]]

在一列中找到平均值

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.]


在 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

在 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

按降序对 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]]

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]]







将 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}]

检查 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




创建一个 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.]]]

在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]

从 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]]







不截断地打印完整的 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]

将 Numpy 转换为列表

import numpy as np


















































































































































































































the_array = np.array([[1, 2], [3, 4]])






print(the_array.tolist())

Output:

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

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

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]

计算 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]

使用 Python 中的值创建 3D NumPy 数组

import numpy as np


















































































































































































































the_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 np



















































































































































 




















































































































x = 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 = True
arr[:x.shape[0], :x.shape[1], 0] = x
arr[:y.shape[0], :y.shape[1], 1] = y
arr[:z.shape[0], :z.shape[1], 2] = z
print(arr.mean(axis=2))

Output:

[[3.0 2.0 3.0]
 [4.666666666666667 4.0 5.0]]

从 Numpy 数组中删除 nan 值

Example 1

import numpy as np



















































































































































 




















































































































x = np.array([np.nan, 2, 3, 4])
x = x[~np.isnan(x)]
print(x)

Output:

[2. 3. 4.]

Example 2

import numpy as np



















































































































































 




















































































































x = 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 np



















































































































































 




















































































































the_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 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]


Numpy 将 1d 数组重塑为 1 列的 2d 数组

import numpy as np


















































































































































































































arr = 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 np


















































































































































































































thearray = np.array([[1, 2], [3, 4], [5, 6]])
print(thearray)

Output:

[[1 2]







 [3 4]



 [5 6]]

创建重复一行

import numpy as np



















































































































































 




















































































































the_array = np.array([1, 2, 3])


repeat = 3

 


































new_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 np


















































































































































































































the_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 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.]


计算每一行的平均值

import numpy as np



















































































































































 




















































































































the_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 np



















































































































































 




















































































































the_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 np



















































































































































 




















































































































the_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 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




在 Python 中附加 NumPy 数组

import numpy as np


















































































































































































































the_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 np



















































































































































 




















































































































thearr = [[True, False], [True, True]]
thebool = np.any(thearr)
print(thebool)

 
















 















thearr = [[False, False], [False, False]]
thebool = np.any(thearr)
print(thebool)

Output:

True





False




获得 NumPy 数组的转置

import numpy as np



















































































































































 




















































































































the_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 np



















































































































































 




















































































































type1 = 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:

int32































































float64















































<U1



































<U5


























float64























['Canad' 'Austr']

获得NumPy数组的形状

import numpy as np



















































































































































 




















































































































array1d = 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 np



















































































































































 




















































































































array1d = np.array([1, 2, 3, 4, 5, 6])


print(array1d.ndim)  # 1
 


































array2d = np.array([[1, 2, 3], [4, 5, 6]])
print(array2d.ndim)  # 2
 












array3d = 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:

1



2

3

重塑 NumPy 数组

import numpy as np



















































































































































 




















































































































thearray = 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 np



















































































































































 




















































































































thearray = 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 np



















































































































































 




















































































































thelist = [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 数组

import numpy as np



















































































































































 




















































































































array1d = np.arange(5)  # 1 row and 5 columns
print(array1d)




 


































array1d = np.arange(0, 12, 2)  # 1 row and 6 columns
print(array1d)

 












array2d = np.arange(0, 12, 2).reshape(2, 3)  # 2 rows 3 columns
print(array2d)

 






array3d = np.arange(9).reshape(3, 3)  # 3 rows and columns
print(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 np



















































































































































 




















































































































array1d = 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 np



















































































































































 




















































































































thearray = 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+46































































 3.59381366e+50 2.78255940e+54 2.15443469e+58 1.66810054e+62















































 1.29154967e+66 1.00000000e+70]

创建 Zeros NumPy 数组

import numpy as np



















































































































































 




















































































































array1d = 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 np



















































































































































 




















































































































array1d = 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 np



















































































































































 




















































































































array1d = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































print(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 np



















































































































































 




















































































































print(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 np



















































































































































 




















































































































array1d = np.array([1, 2, 3, 4, 5, 6])


print(array1d[0])   # Get first value
print(array1d[-1])  # Get last value
print(array1d[3])   # Get 4th value from first
print(array1d[-5])  # Get 5th value from last
 












# Get multiple values
print(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 col
print(array2d[0, 1])   # Get first row second col
print(array2d[0, 2])   # Get first row third col
 


print(array2d[0, 1])   # Get first row second col 
print(array2d[1, 1])   # Get second row second col
print(array2d[2, 1])   # Get third row second col

Output:

1


































































6















































4



































2


























[1 6]























----------



















[[1 2 3]
















 [4 5 6]














 [7 8 9]]











----------










1









2









3









2









5







8

多维数组中的 NumPy 索引

import numpy as np



















































































































































 




















































































































array3d = 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]]]























1



















2
















3














4











5










6









7









8









9









10







11





12

NumPy 单维切片示例

import numpy as np



















































































































































 




















































































































array1d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 




















































print(array1d[4:])  # From index 4 to last index
 
















print(array1d[:4])  # From index 0 to 4 index
 












print(array1d[4:7])  # From index 4(included) up to index 7(excluded)
 











print(array1d[:-1])  # Excluded last element
 



print(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 order
 

print(array1d[-2::-2])  # All even numbers in reversed order
 
print(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 np



















































































































































 




















































































































array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

 




















































print("-" * 10)
print(array2d[:, 0:2])  # 2nd and 3rd col
 















print("-" * 10)
print(array2d[1:3, 0:3])  # 2nd and 3rd row
 











print("-" * 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 np



















































































































































 




















































































































array2d = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































array1 = 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 np



















































































































































 




















































































































array1 = 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.0































































Std:  17.07825127659933















































Var:  291.6666666666667



































Sum:  210


























Prod:  720000000

Where 函数的 NumPy 示例

import numpy as np



















































































































































 




















































































































before = np.array([[1, 2, 3], [4, 5, 6]])

 




















































# If element is less than 4, mul by 2 else by 3

after = np.where(before < 4, before * 2, before * 3)
 















print(after)

Output:

[[ 2  4  6]
































































 [12 15 18]]

Select 函数的 NumPy 示例

import numpy as np



















































































































































 




















































































































before = np.array([[1, 2, 3], [4, 5, 6]])

 




















































# If element is less than 4, mul by 2 else by 3

after = np.select([before < 4, before], [before * 2, before * 3])
 















print(after)

Output:

[[ 2  4  6]
































































 [12 15 18]]

选择函数的 NumPy 示例

import numpy as np



















































































































































 




















































































































before = 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 np



















































































































































 




















































































































thearray = 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 np



















































































































































 




















































































































array1 = 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]

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYXfjhAf' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片