import numpy as np
# 创建数组,dtype指定数组类型
a = np.array(range(10), dtype='int32')# np.arange(初始值,结束值,步长)
b = np.arange(1,10,2, dtype='float')# 结果为array([1., 3., 5., 7., 9.])# 创建bool类型的数组,dtype='bool'或者dtype=np.bool
c = np.array([1,2,0,0,-1,9,-9], dtype='bool')# 结果为array([ True, True, False, False, True, True, True])# 修改数组的数据类型
a = a.astype('float')
b = b.astype('int64')
c = c.astype('int')# 生成随机数
c = np.random.random(7)# 修改小数位数
c = np.round(c,2)# 生成二维数组
d = np.array([[1,2,3,4],[4,6,7,8]])# 查看数组的形状
d.shape
# 修改数组的形状
d = d.reshape(4,2)# 转化为一维数组
d = d.reshape(1,8)# array([[1, 2, 3, 4, 4, 6, 7, 8]])这个还不是一维数组
d = d.flatten()# 正确,如array([1, 2, 3, 4, 4, 6, 7, 8])# 数组和数的计算,数组中的每一个元素都和数进行计算
a = a +3
b = b *6# 数组与数组的运算,具有广播效应
e = np.array([[1,2,3],[5,6,8]])
f = np.array([[1],[2]])
g = np.array([2,4,6])
e - f
e * g
e - g
e / f
# 数组的转置
e.transpose()
e.T
e.swapaxes(1,0)# 交换轴# 数组的切片和索引
h = np.array([[1,2,3,4,5],[21,22,34,23,44],[1,2,12,43,65]])
h[1,1]# 取第2行、第二列的元素
h[:,[1,3]]# 取第2、4列
h[:,[1,3]]= h[:,[3,1]]# 列交换# 数组的修改
h[1,1]=0# 将第2行、第二列的元素改为0# 将数组中小于10的数置为0,大于10的数置为20
i = np.arange(24).reshape(3,8)
i = np.where(i <10,0,20)# 将数组中小于10的数置为0,大于20的数置为1
j = np.arange(24).reshape(4,6)
j = np.where(j <10,0, j >20,1)# clip函数的使用
k = np.arange(12).reshape(2,6)
k = np.clip(k,4,8)# 将k中小于4的数置为4,大于8的数置为8# 数组的拼接
l = np.arange(6).reshape(2,3)
m = np.arange(5,11).reshape(2,3)
n = np.vstack((l, m))# 竖直拼接
o = np.hstack((l, m))# 水平拼接# 获取最大值,最小值的位置
p = np.argmax(l,0)# 0表示行方向,行与行相比较,1表示列方向,列与列相比较
q = np.argmin(o,1)