NumPy 高维数组降维方法详细分析


import numpy as np

a = np.arange(64).reshape([4,4,4])
# [[[ 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]]]
print(a)

# 对三维数组a进行降维打击
a_reshape = a.reshape(-1)
# [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]
print('reshape方法:\n',a_reshape)
c_flat = []
for x in a.flat:
    c_flat.append(x)
# [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]
print('flat迭代器:\n',c_flat)
d_flatten = a.flatten()
# [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]
print('flatten方法:\n',d_flatten)
e_ravel = a.ravel()
# [ 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]
print('ravel方法:\n',e_ravel)

f_resize = a.resize(64)
# None   resize   没有返回值,改变的是原数组
print('resize方法:\n',f_resize)
# [ 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]
print(a)


你可能感兴趣的:(Python,python,numpy)