数组的切片与索引
一维NumPy数组的切片操作与Python列表的切片一样
- 通过下标选择该数组3-7的数
In [1]: import numpy as np In [2]: a = np.arange(9) In [3]: a[3:7] Out[3]: array([3, 4, 5, 6]) - 下标范围0-7,下标每次递增2
In [6]: a[:7:2] Out[6]: array([0, 2, 4, 6]) - 通过负值翻转数组
In [7]: a[::-1] Out[7]: array([8, 7, 6, 5, 4, 3, 2, 1, 0])
处理数组形状
In [8]: b = np.arange(24).reshape(2,3,4)
In [9]: b
Out[9]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
- 拆解(ravel)
可以利用ravel()函数将多维数组变成一维数组
In [10]: b.ravel() Out[10]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) - 拉直(Flatten)
其功能与ravel()相同,不同的是flatten()返回的是真实的数组,需要分配新的空间;而ravel()返回的只是数组的视图
In [11]: b.flatten() Out[11]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) - 用元祖指定数组形状
除reshape()函数外,还可以用元祖来定义数组的形状
In [13]: b.shape = (6,4) In [14]: b Out[14]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]) - 转置(transpose)
转置是一种数据变换方法;对于二维表而言,转置就意味着行变成列,列变成行
In [16]: b.transpose() Out[16]: array([[ 0, 4, 8, 12, 16, 20], [ 1, 5, 9, 13, 17, 21], [ 2, 6, 10, 14, 18, 22], [ 3, 7, 11, 15, 19, 23]]) - 调整大小(resize)
函数resize()的作用类似于reshape(),但是会改薄案所作用的数组
In [18]: b Out[18]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
结束语
如果您对这篇文章有什么意见或者建议,请评论与我讨论.
如果您觉得还不错的话~可以点个喜欢鼓励我哦.
如果您想和我一起学习,请毫不吝啬的私信我吧~













网友评论