Python-arange()、reshape()与argmax()

本文探讨了Python numpy库中的三个关键函数:arange()用于创建一维数组,reshape()用于改变数组维度,argmax()则用于获取数组中最大值的索引。特别解释了argmax()函数的参数out的含义,指出其作用在于接收并存储计算结果,但不影响输出大小,仅在特定条件下避免错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录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]: 
#改成23列
array([[0, 1, 2],
       [3, 4, 5]])
In[6]: a.reshape(3,2)
Out[6]: 
#改成32列
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。。。(简直就是废话,这有什么卵用)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值