亲宝软件园·资讯

展开

numpy降维方法

Yuzzz. 人气:0

numpy中的降维方法:

代码示例:

import numpy as np

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

c = []
for x in a.flat:
    c.append(x)
print('flat迭代器降一维:\n', c)
d = a.flatten()
print('flatten方法降一维:\n', d)
e = a.ravel()
print('ravel方法降一维:\n', e)
g = np.squeeze(a)
print('squeeze方法降一维:\n', g)
f = a.reshape(-1)
print('reshape方法降一维:\n', f)
a.resize((1, 6))
print('resize方法:\n', a)

结果:

flat迭代器降一维:
[1, 2, 3, 4, 5, 6]
flatten方法降一维:
[1 2 3 4 5 6]
ravel方法降一维:
[1 2 3 4 5 6]
squeeze方法降一维:
[[1 2 3]
[4 5 6]]
reshape方法降一维:
[1 2 3 4 5 6]
resize方法:
[[1 2 3 4 5 6]]

补: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)

加载全部内容

相关教程
猜你喜欢
用户评论