Numpy的索引操作

切片索引

numpy的切片索引是从0开始,左闭右开的。

Numpy.linspace

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

含义是返回闭区间 [ s t a r t , s t o p ] [start,stop] [start,stop]分布均匀的num个点,这里值得强调的是,返回的点中必须包含start和stop,这意味着每个点之间的间隔为:
d = s t o p − s t a r t n u m − 1 d=\frac{stop-start}{num-1} d=num1stopstart
所以一般的当开始点为0时,间隔有时会出乎你的意料。

Numpy索引的选择操作

与pandas类似Numpy中也有类似的操作可以实现查找最大值的哪一个等等的操作,比如:
在这里插入图片描述
上图是通过如下代码生成的:

np.random.seed(0)
trainx = np.vstack((np.random.randn(50,2),np.random.randn(50,2)+4))
traint = np.hstack((-1*np.ones(50),np.ones(50)))[:,None]
plt.figure()
c0 = np.where(traint==-1)[0]
c1 = np.where(traint==1)[0]
plt.plot(trainx[c0,0],trainx[c0,1],'bo',markersize=10)
plt.plot(trainx[c1,0],trainx[c1,1],'ro',markersize=10)

我们想把红色点中最下方的点变为蓝色该如何实现呢?也许下面的代码对你有帮助:

print(trainx)
print(trainx[:,1])
print(max(trainx[:,1]))
print(np.where(trainx[:,1] == max(trainx[:,1]))[0][0])

尝试观察上面的输出,你应该能得到:

index = np.where(trainx[:,1] == min(trainx[50:100,1]))[0][0]
traint[index][0] *= -1

代码将这个点的数值乘以-1,得到相反的结果再画图可得:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值