python基础-numpy

np.random()
 np.random.rand(3,2) #随机生成【32】大小的矩阵
array([[0.98766853, 0.09140474],
       [0.85365579, 0.71327129],
       [0.22873142, 0.05369397]])
>>> np.random.randint(10,size=5) #随机生成(0-10)int整形,大小=5
array([3, 2, 2, 9, 7])
np.arange() 借鉴
  1. 一个参数时,参数值为终点,起点取默认值0,步长取默认值1
>>> np.arange(5) 
array([0, 1, 2, 3, 4])
  1. 两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。包前不包后
>>> np.arange(5,10)
array([5, 6, 7, 8, 9])
  1. 三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长;步长支持小数。
>>> np.arange(5,10,2) 
array([5, 7, 9])
array([[1, 2, 3, 4, 5, 6]])
>>> c.shape
(1, 6)
>>> c.ndim
2
>>> a=np.array([1,2,3,4,5,6])
>>> a.shape
(6,)
>>> a.ndim
1

参考
稍微一看,shape为(x,)和shape为(x,1)几乎一样,都是一维的形式。其实不然:

(x,)意思是一维数组,数组中有x个元素
(x,1)意思是一个x维数组,每行有1个元素

reshape() 参考

numpy中reshape函数的三种常见相关用法
1、numpy.arange(n).reshape(a, b) 依次生成n个自然数,并且以a行b列的数组形式显示

np.arange(16).reshape(2,8) #生成16个自然数,以28列的形式显示
# Out: 
# array([[ 0,  1,  2,  3,  4,  5,  6,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15]])

2、mat (or array).reshape(c, -1) 必须是矩阵格式或者数组格式,才能使用 .reshape(c, -1) 函数, 表示将此矩阵或者数组重组,以 c行d列的形式表示

arr.shape    # (a,b)
arr.reshape(m,-1) #改变维度为m行、d列 (-1表示列数自动计算,d= a*b /m )
arr.reshape(-1,m) #改变维度为d行、m列 (-1表示行数自动计算,d= a*b /m )

-1的作用: 自动计算d:d=数组或者矩阵里面所有的元素个数/c, d必须是整数,不然报错)
(reshape(-1, m)即列数固定,行数需要计算)
3、

  • numpy.arange(a,b,c) 从 数字a起, 步长为c, 到b结束,生成array 【a,b)
  • numpy.arange(a,b,c).reshape(m,n) :将array的维度变为m 行 n列。
>>> np.arange(1,11,2)              
array([1, 3, 5, 7, 9])
>>> np.arange(1,12,2).reshape(2,-1) 
array([[ 1,  3,  5],
       [ 7,  9, 11]])

参考:

array([[1, 2, 3],
       [4, 5, 6]])
>>> c=c.reshape(3,2) 
>>> c
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> c=c.reshape(-1,6) 
>>> c
array([[1, 2, 3, 4, 5, 6]])
>>> c=c.reshape(6,-1) 
>>> c
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

你可能感兴趣的:(python,python,numpy,开发语言)