一维,多维array的切片

						<!-- flowchart 箭头图标 勿删 -->
						<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
						<h2><a id="_0" target="_blank"></a>环境</h2>

python 3.6
numpy
1.背景
今天有人问我numpy中[1:3,None]是啥意思,一开始讲得云里雾里,后来终于理清了,我们逐步深入研究♂(滑稽)
2.一维情况

import  numpy as np
a=np.array([1,2,3,4])
print(a[0:3:2])

 
 
  • 1
  • 2
  • 3

输出

[1 3]

 
 
  • 1

一维应该都知道吧 跟list差不多 [Start:End:Step] 注意是不包含End
2.二维情况
在这里插入图片描述

import  numpy as np
a=np.array([[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]])
print(a[0:4:2,0:4:2])

 
 
  • 1
  • 2
  • 3

输出

[[11 13]
 [31 33]]

 
 
  • 1
  • 2

所以第0维取0到4步长为2 ,第1维也取0到4步长为2 ,所以意思是[第0维,第1维],然后多维类推嘛,应该能理解了吧
3.关于None
再说说一开始的[:,None]
emmmm简单说就是说它增加了一个维度
但还是有些不同的,看例子

import  numpy as np
a=np.array([[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]])
print('0维为None:')
print(a[None,0:4])
print('1维为None:')
print(a[0:4,None])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

输出

0维为None:
[[[11 12 13 14]
  [21 22 23 24]
  [31 32 33 34]
  [41 42 43 44]]]
1维为None:
[[[11 12 13 14]]

[[21 22 23 24]]

[[31 32 33 34]]

[[41 42 43 44]]]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

看下官方文档,链接

Note:
Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. 
Slice objects can be used in the construction in place of the [start:stop:step] notation.
For example, x[1:10:5,::-1] can also be implemented as obj = (slice(1,10,5), slice(None,None,-1)); 
x[obj].This can be useful for constructing generic code that works on arrays of arbitrary dimension.

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
numpy.newaxis
The newaxis object can be used in all slicing operations to create an axis of length one.
newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.

 
 
  • 1
  • 2
  • 3

它巴拉巴拉的意思就是numpy.newaxis效果和None是一样的,None是它的别名

print(None is np.newaxis)
True

 
 
  • 1
  • 2

(话说为了少打点字(len(None)<len(numpy.newaxis)),可能就会让初学者看不懂- -,但是告诉他们答案我想他们肯定想暴打写代码的人♂(呼应前文滑稽))
想更详细的知道numpy.newaxis的可以自己去搜搜啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值