Numpy模块学习
numpy的基本属性
| import numpy as np
array = np.array([[1,2,3], [2,3,4]]) print(array)
print('number of dim:',array.ndim) print('shape:',array.shape) print('size:',array.size)
|
numpy创建的array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import numpy as np
a = np.array([2,23,4],dtype=np.int) print(a) print(a.dtype)
a = np.zeros((4,2)) print(a)
a = np.ones((4,2)) print(a)
a = np.ones((4,2),dtype=int) print(a)
a = np.empty((3,4)) print(a)
a = np.arange(10) a = np.arange(10,20,2) print(a)
a = np.arange(12).reshape((3,4)) print(a)
a = np.linspace(10,20,20) print(a)
a = a.reshape((4,5)) print(a)
|
numpy的基础运算1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import numpy as np
a = np.array([10,20,30,40]) b = np.arange(4) print(a,b) c = a + b print(c)
c = c**2 print(c)
c = 10*np.sin(a) print(c)
print(a>10) print(a==10)
a = np.array([[2,1], [0,3]]) c=a*a c_dot=np.dot(a,a) c_dot_2=a.dot(a) print(c)
print(c_dot)
a = np.random.random((2,4)) print(a)
a = np.array([[1,2,3,4,5], [9,10,11,12,13]]) print(np.sum(a)) print(np.sum(a,axis=1)) print(np.sum(a,axis=0)) print(np.min(a)) print(np.max(a)) print(np.min(a,axis=1))
|
numpy基础运算2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import numpy as np
a = np.arange(2,14).reshape(3,4) print(a)
print(np.argmin(a)) print(np.argmax(a)) print(np.mean(a)) print(np.mean(a,axis=0)) print(np.mean(a,axis=1)) print(np.median(a)) print(np.cumsum(a)) print(np.diff(a))
print(np.nonzero(a))
print(np.sort(a)) print(np.transpose(a))
print(a.T)
print(np.clip(a,5,9))
|
numpy的索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import numpy as np
a = np.arange(3,15).reshape(3,4)
print(a)
print(a[2]) print(a[2][0]) print(a[2,0]) print(a[1,1:]) print(a[1,1:3])
for row in a: print(row)
for column in a.T: print(column)
print(a.flatten()) for item in a.flat: print(item)
for item in a.flatten(): print(item)
|
numpy的array合并
| import numpy as np
a = np.array([1,1,1]) b = np.array([2,2,2]) c = np.vstack((a,b)) print(c)
|
| import numpy as np
a = np.array([[1, 1, 1]]) b = np.array([[2, 2, 2]]) c = np.array([[3, 3, 3]])
d = np.concatenate((a,b,c),axis=0) print(d)
d = np.concatenate((a,b,c),axis=1) print(d)
|
下面单独拿出来说一下关于array的维度的问题和newaxis这个函数的理解
比如:
| print(np.transpose(a)) print(a.T)
|
一个二维的数组才有转置,一个一维的数组把他转置后,再放回一维数组那还是原来的一维数组,如果我们想让它输出一列那样,那就是一个二维的数组了,所以此时我们就需要增加维数。
这里引入一个函数$numpy.axis$ 可以用来增加数组的维数
array的分割
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import numpy as np
a = np.arange(12).reshape((3,4)) print(a)
print(np.split(a,4,axis=1))
print(np.array_split(a,3,axis=1))
print('111') print(np.vsplit(a, 3))
print(np.hsplit(a, 2))
|
numpy的copy&deepcopy