numpy的基本属性
import numpy as np
array = np.array([[1, 2, 3], [2, 3, 4]], np.float16)
print(array)
print('number of dim', array.ndim)
print('shape', array.shape)
print('size', array.size)
print('type', array.dtype)
a = np.zeros((3, 4), np.int)
a2 = np.arange(20)
a3=np.linspace(1,100,5)
print(a)
print(a2)
print(a3)
numpy的常用函数
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.arange(6).reshape((2, 3))
print('a=', a)
print('b=', b)
print('a*b=', a * b)
c = np.random.random((2, 4))
print('c=', c)
print('sum=', np.sum(c))
print('max', np.max(c, axis=0))
print('min', np.min(c, axis=1))
print('平均值', np.mean(c))
print('平均值2', np.average(c))
print('中位数', np.median(c))
print('累加', np.cumsum(c))
print('累差', np.diff(a))
print('索引值', np.argmax(c))
print('非0', np.nonzero(c))
print('排序',np.sort(c))
print('反向',np.transpose(c))
print('截取',np.clip(c,0.3,0.6))#所有小于0.3的都等于0.3,所有大于0.6的都等于0.6
数据的获取与遍历
import numpy as np
a = np.arange(2, 12)
print(a)
print(a[2])
b = a.reshape((2, 5))
print(b)
print(b[1][1])
print(b[1, 1])
print(b[0, :])
print('flat',a.flatten())
for row in b:
print('row',row)
合并与分割
import numpy as np
a = np.array([1, 1, 1])
b = np.array([2, 3, 4])
c = np.vstack((a, b)) # 上下合并
print(c)
print(a.shape, c.shape)
d = np.hstack((a, b)) # 左右合并
print(d)
print(a.shape, d.shape)
f = a[np.newaxis, :]
print(f)
print(f.shape)
g = np.concatenate((a, b, a, b), axis=0) # 可以指定在哪个维度进行合并
print(g)
h = np.arange(12).reshape((3, 4))
print(h)
print(np.split(h, 2, axis=1)) # 分割成n块
print(np.array_split(h, 3, axis=1)) # 进行不等的分割
print(np.vsplit(h, 3)) # 纵向分割
print(np.hsplit(h, 2)) # 横向分割)
复制
import numpy as np
a=np.arange(4)
b=a
a[0]=3
print(a,b)
print(a is b)
c=a.copy()
a[2]=0
print(a,c)
print(a is c)