(给Python开发者加星标,提升Python技能)
来源: CSDN-逐梦er
blog.csdn.net/qq_43328040/article/details/108700665
一.数组上的迭代
NumPy 包含一个迭代器对象numpy.nditer。它是一个有效的多维迭代器对象,可以用于在数组上进行迭代。数组的每个元素可使用 Python 的标准Iterator接口来访问。
import numpy as npa = np.arange(0, 60, 5)a = a.reshape(3, 4)print(a)for x in np.nditer(a): print(x)
[[ 0 5 10 15] [20 25 30 35] [40 45 50 55]]0510152025303540455055
如果两个数组是可广播的,nditer组合对象能够同时迭代它们。假设数 组a具有维度 3X4,并且存在维度为 1X4 的另一个数组b,则使用以下类型的迭代器(数组b被广播到a的大小)。
import numpy as npa = np.arange(0, 60, 5)a = a.reshape(3, 4)print(a)b = np.array([1, 2, 3, 4], dtype=int)print(b)for x, y in np.nditer([a, b]): print(x, y)
[[ 0 5 10 15] [20 25 30 35] [40 45 50 55]][1 2 3 4]0 15 210 315 420 125 230 335 440 145 250 355 4
二.数组形状修改函数
1.ndarray.reshape
函数在不改变数据的条件下修改形状,参数如下:
ndarray.reshape(arr, newshape, order)
其中:
import numpy as npa = np.arange(8)print(a)b = a.reshape(4, 2)print(b)
2.ndarray.flat
函数返回数组上的一维迭代器,行为类似 Python 内建的迭代器。
import numpy as npa = np.arange(0, 16, 2).reshape(2, 4)print(a)# 返回展开数组中的下标的对应元素print(list(a.flat))
[[ 0 2 4 6] [ 8 10 12 14]][0, 2, 4, 6, 8, 10, 12, 14]
3.ndarray.flatten
函数返回折叠为一维的数组副本,函数接受下列参数:
ndarray.flatten(order)其中:order:‘C’ — 按行,‘F’ — 按列,‘A’ — 原顺序,‘k’ —元素在内存中的出现顺序。
import numpy as npa = np.arange(8).reshape(2, 4)print(a)# default is column-majorprint(a.flatten())print(a.flatten(order='F'))
[[0 1 2 3] [4 5 6 7]][0 1 2 3 4 5 6 7][0 4 1 5 2 6 3 7]
三.数组翻转操作函数
1.numpy.transpose
函数翻转给定数组的维度。如果可能的话它会返回一个视图。函数接受下列参数:
numpy.transpose(arr, axes)
其中:
• arr:要转置的数组• axes:整数的列表,对应维度,通常所有维度都会翻转。
import numpy as npa = np.arange(24).reshape(2, 3, 4)print(a)b = np.array(np.transpose(a))print(b)print(b.shape)
[[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]][[[ 0 12] [ 4 16] [ 8 20]] [[ 1 13] [ 5 17] [ 9 21]] [[ 2 14] [ 6 18] [10 22]] [[ 3 15] [ 7 19] [11 23]]](4, 3, 2)
b = np.array(np.transpose(a, (1, 0, 2)))print(b)print(b.shape
[[[ 0 1 2 3] [12 13 14 15]] [[ 4 5 6 7] [16 17 18 19]] [[ 8 9 10 11] [20 21 22 23]]](3, 2, 4)
2. numpy.ndarray.T
该函数属于ndarray类,行为类似于numpy.transpose.
import numpy as npa = np.arange(12).reshape(3, 4)print(a)print(a.T)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]][[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
3.numpy.swapaxes
函数交换数组的两个轴。这个函数接受下列参数:
– numpy.swapaxes(arr, axis1, axis2)
– 参数:
• arr:要交换其轴的输入数组• axis1:对应第一个轴的整数• axis2:对应第二个轴的整数
import numpy as npa = np.arange(8).reshape(2, 2, 2)print(a)print(np.swapaxes(a, 2, 0))
[[[0 1] [2 3]] [[4 5] [6 7]]][[[0 4] [2 6]] [[1 5] [3 7]]]
4.numpy.rollaxis
s 函数向后滚动特定的轴,直到一个特定位置。这个函数
接受三个参数: