记录Python学习中numpy模块里的几个函数:arange()、reshape()与argmax()
arange():创建一维数组
In[2]: import numpy as np
In[3]: a=np.arange(6)
In[4]: a
Out[4]:
array([0, 1, 2, 3, 4, 5])
reshape:改变数组维度
In[5]: a.reshape(2,3)
Out[5]:
#改成2行3列
array([[0, 1, 2],
[3, 4, 5]])
In[6]: a.reshape(3,2)
Out[6]:
#改成3行2列
array([[0, 1],
[2, 3],
[4, 5]])
In[7]: a.reshape(-1,6)
Out[7]:
#不知道几行的情况下确定是6列
array([[0, 1, 2, 3, 4, 5]])
In[8]: a.reshape(6,-1)
Out[8]:
#确定是6行,不知道几列
array([[0],
[1],
[2],
[3],
[4],
[5]])
In[9]: a.reshape(-1)
Out[9]:
#不分行列
array([0, 1, 2, 3, 4, 5])
In[10]: a.reshape(-1,5)
ValueError: cannot reshape array of size 6 into shape (5)
argmax():获取最大值的索引
In[26]: a=np.array([3,2,1,4,5,6])
In[27]: a.reshape(3,2)
Out[27]:
array([[3, 2],
[1, 4],
[5, 6]])
In[28]: a
Out[28]:
#a的值并没有改变,所以需要reshape后赋值给b
array([3, 2, 1, 4, 5, 6])
In[29]: b=a.reshape(3,2)
In[30]: b
Out[30]:
array([[3, 2],
[1, 4],
[5, 6]])
In[31]: np.argmax(a)
Out[31]:
5
In[32]: np.argmax(b)
Out[32]:
#不指定行或列时,默认将数组平铺取最大值索引
5
In[33]: np.argmax(b,axis=0)
Out[33]:
#0代表列,取每一列的最大值
array([2, 2], dtype=int64)
In[34]: np.argmax(b,axis=1)
Out[34]:
#1代表行,取每一行的最大值
array([0, 1, 1], dtype=int64)
说明:argmax(a, axis=None, out=None)中out的含义
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
In[56]: a=np.arange(6).reshape(2,3)
In[57]: a
Out[57]:
array([[0, 1, 2],
[3, 4, 5]])
In[58]: res1=np.array([6,7])
In[59]: res2=np.array([8,9,0])
In[60]: b=np.argmax(a,axis=0,out=res2)
In[61]: c=np.argmax(a,axis=1,out=res1)
In[62]: d=np.argmax(a,axis=1,out=res2)
ValueError: output array does not match result of np.argmax.
In[63]: d=np.argmax(a,axis=0,out=res1)
ValueError: output array does not match result of np.argmax.
In[64]: print(b,c)
[1 1 1] [2 2]
分析:只有当out的形状与输出的形状相同时才不会报错,而数组out的大小并不会对结果产生影响。所以我认为out的作用可能是判定输出是否是目标形状。。。
In[69]: e=np.argmax(a,axis=0)
In[70]: e
Out[70]:
array([1, 1, 1], dtype=int64)
In[71]: type(e)
Out[71]:
numpy.ndarray
In[72]: b
Out[72]:
array([1, 1, 1])
In[73]: type(b)
Out[73]:
numpy.ndarray
In[74]: b.dtype
Out[74]:
dtype('int32')
虽然使用out后输出的大小没有变化,但是元素类型从int64变为了int32。。。(简直就是废话,这有什么卵用)