熬夜整理了11种Numpy的高级操作,每一种都有参数解释与小例子辅助说明,希望对你有所帮助,看完记得点个赞收藏起呀哇~
01数组上的迭代
NumPy 包含一个迭代器对象numpy.nditer。它是一个有效的多维迭代器对象,可以用于在数组上进行迭代。数组的每个元素可使用 Python 的标准Iterator接口来访问。
import numpy as np
a = 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]]
0
5
10
15
20
25
30
35
40
45
50
55
如果两个数组是可广播的,nditer组合对象能够同时迭代它们。假设数 组a具有维度 3X4,并且存在维度为 1X4 的另一个数组b,则使用以下类型的迭代器(数组b被广播到a的大小)。
import numpy as np
a = 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 1
5 2
10 3
15 4
20 1
25 2
30 3
35 4
40 1
45 2
50 3
55 4
02 数组形状修改函数
1.ndarray.reshape
函数在不改变数据的条件下修改形状,参数如下:
ndarray.reshape(arr, newshape, order)
import numpy as np
a = np.arange(8)
print(a)
b = a.reshape(4, 2)
print(b)
[0 1 2 3 4 5 6 7]
[[0 1]
[2 3]
[4 5]
[6 7]]
2.ndarray.flat
函数返回数组上的一维迭代器,行为类似 Python 内建的迭代器。
import numpy as np
a = 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 np
a = np.arange(8).reshape(2, 4)
print(a)
# default is column-major
print(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]
03 数组翻转操作函数
1.numpy.transpose
函数翻转给定数组的维度。如果可能的话它会返回一个视图。函数接受下列参数:
numpy.transpose(arr, axes)
其中:
-
arr:要转置的数组
-
axes:整数的列表,对应维度,通常所有维度都会翻转。
import numpy as np
a = 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)
-
numpy.ndarray.T
该函数属于ndarray类,行为类似于numpy.transpose.
import numpy as np
a = 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 np
a = 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
numpy.rollaxis() 函数向后滚动特定的轴,直到一个特定位置。这个函数接受三个参数:
numpy.rollaxis(arr, axis, start)
其中:
-
arr:输入数组
-
axis:要向后滚动的轴,其它轴的相对位置不会改变
-
start:默认为零,表示完整的滚动。会滚动到特定位置。
import numpy as np
a = np.arange(8).reshape(2,2,2)
print(a)
print(np.rollaxis(a,2))
print(np.rollaxis(a,2,1))
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
[[[0 2]
[4 6]]
[[1 3]
[5 7]]]
[[[0 2]
[1 3]]
[[4