numpy函数:arange(), reshape()用法

arange()用于生成一维数组 
reshape()将一维数组转换为多维数组

 

import numpy as np

print('默认一维为数组:', np.arange(5))
print('自定义起点一维数组:',np.arange(1, 5))
print('自定义起点步长一维数组:',np.arange(2, 10, 2))
print('二维数组:', np.arange(8).reshape((2, 4)))
print('三维数组:', np.arange(60).reshape((3, 4, 5)))

print('指定范围三维数组:',np.random.randint(1, 8, size=(3, 4, 5)))

 

输出结果:

默认一维数组: [0 1 2 3 4]
自定义起点一维数组: [1 2 3 4]
自定义起点步长一维数组: [2 4 6 8]
二维数组: [[0 1 2 3]
 [4 5 6 7]]
三维数组: [[[ 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]]]
指定范围三维数组: [[[2 3 2 1 5]
  [6 5 5 6 7]
  [4 4 6 5 3]
  [2 2 3 5 6]]

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

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

 [[7 6 5 3]
  [5 6 5 4]
  [6 5 7 1]]]

  

==========

应用: 

四个函数都是对多维数组进行降维(降至一维)

使用方法:

import numpy as np

a = np.arange(64).reshape([4,4,4])
print(a)

#对三维数组a进行降维打击
b = a.reshape(-1)
print('reshape方法:\n',b)
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)
a.resize(64)
print('resize方法:\n',a)

#
[[[ 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]]]
reshape方法:
 [ 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]
flat迭代器:
 [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]
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]
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]
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]

 

posted @ 2019-07-04 11:24  peterwong666  阅读(3492)  评论(0编辑  收藏  举报