本节重点介绍 NumPy 数组元素的增删改查操作,主要有以下方法:
函数名称 | 描述说明 |
---|---|
resize | 返回指定形状的新数组。 |
append | 将元素值添加到数组的末尾。 |
insert | 沿规定的轴将元素值插入到指定的元素前。 |
delete | 删掉某个轴上的子数组,并返回删除后的新数组。 |
argwhere | 返回数组内符合条件的元素的索引值。 |
unique | 用于删除数组中重复的元素,并按元素值由大到小返回一个新数组。 |
numpy.resize() 返回指定形状的新数组。
使用示例:
- import numpy as np
- a = np.array([[1,2,3],[4,5,6]])
- print(a)
- #a数组的形状
- print(a.shape)
- b = np.resize(a,(3,2))
- #b数组
- print (b)
- #b数组的形状
- print(b.shape)
- #修改b数组使其形状大于原始数组
- b = np.resize(a,(3,3))
- print(b)
输出结果为:
这里需要区别 resize() 和 reshape() 的使用方法,它们看起来相似,实则不同。resize 仅对原数组进行修改,没有返回值,而 reshape 不仅对原数组进行修改,同时返回修改后的结果。
看一组示例,如下所示:
- In [1]: import numpy as np
- In [2]: x=np.arange(12)
- #调用resize方法
- In [3]: x_resize=x.resize(2,3,2)
-
- In [4]: x
- Out[4]:
- array([[[ 0, 1],
- [ 2, 3],
- [ 4, 5]],
- [[ 6, 7],
- [ 8, 9],
- [10, 11]]])
-
- In [5]: x_resize
- #返回None使用print打印
- In [6]: print(x_resize)
- None
- #调用reshape方法
- In [7]: x_shape=x.reshape(2,3,2)
- #返回修改后的数组
- In [8]: x_shape
- Out[8]:
- array([[[ 0, 1],
- [ 2, 3],
- [ 4, 5]],
-
- [[ 6, 7],
- [ 8, 9],
- [10, 11]]])
-
- In [9]: x
- Out[9]:
- array([[[ 0, 1],
- [ 2, 3],
- [ 4, 5]],
-
- [[ 6, 7],
- [ 8, 9],
- [10, 11]]])
在数组的末尾添加值,它返回一个一维数组。
参数说明:
使用示例:
- import numpy as np
- a = np.array([[1,2,3],[4,5,6]])
- #向数组a添加元素
- print (np.append(a, [7,8,9]))
-
- #沿轴 0 添加元素
- print (np.append(a, [[7,8,9]],axis = 0))
- #沿轴 1 添加元素
- print (np.append(a, [[5,5,5],[7,8,9]],axis = 1))
输出结果为:
表示沿指定的轴,在给定索引值的前一个位置插入相应的值,如果没有提供轴,则输入数组被展开为一维数组。
参数说明:
示例如下:
- import numpy as np
- a = np.array([[1,2],[3,4],[5,6]])
-
- #不提供axis的情况,会将数组展开
- print (np.insert(a,3,[11,12]))
-
- #沿轴 0 垂直方向
- print (np.insert(a,1,[11],axis = 0))
-
- #沿轴 1 水平方向
- print (np.insert(a,1,11,axis = 1))
输出结果如下:
该方法表示从输入数组中删除指定的子数组,并返回一个新数组。它与 insert() 函数相似,若不提供 axis 参数,则输入数组被展开为一维数组。
参数说明:
使用示例:
- import numpy as np
- a = np.arange(12).reshape(3,4)
- #a数组
- print(a)
- #不提供axis参数情况
- print(np.delete(a,5))
-
- #删除第二列
- print(np.delete(a,1,axis = 1))
-
- #删除经切片后的数组
- a = np.array([1,2,3,4,5,6,7,8,9,10])
- print (np.delete(a, np.s_[::2]))
输出结果为:
该函数返回数组中非 0 元素的索引,若是多维数组则返回行、列索引组成的索引坐标。
示例如下所示:
- import numpy as np
- x = np.arange(6).reshape(2,3)
- print(x)
- #返回所有大于1的元素索引
- y=np.argwhere(x>1)
- print(y)
输出结果:
用于删除数组中重复的元素,其语法格式如下:
参数说明:
示例如下:
- import numpy as np
- a = np.array([5,2,6,2,7,5,6,8,2,9])
- print (a)
- #对a数组的去重
- uq = np.unique(a)
- print (uq)
-
- #数组去重后的索引数组
- u,indices = np.unique(a, return_index = True)
- #打印去重后数组的索引
- print(indices)
-
- #去重数组的下标:
- ui,indices = np.unique(a,return_inverse = True)
- print (ui)
- #打印下标
- print (indices)
-
- #返回去重元素的重复数量
- uc,indices = np.unique(a,return_counts = True)
- print (uc)
- 元素出现次数:
- print (indices)
输出结果为: