数组的创建与转变
import numpy as np
t1 = np.array([0,1,2,])
t2 = np.array(range(3))
t3 = np.arange(3)
t1/t2/t3
>>> [0 1 2]
t4 = np.array([random.random() for i in range(3)])
np.round(t4, 2)
>>> [... ... ...]
t5 = np.array(range(3), dtype = 'int')
t5.dtype # 查看数组内部数据类型
>>> 'int64' # 64位电脑自动保存64位
t6 = np.array([1,1,0], dtype = 'bool')
>>> [True True False]
t7.astype('int8') # 转变
>>> [1 1 0]
数组的形状改变
t1 = np.array([[1,1,1],[1,1,1]])
t1.reshape(3,2)
>>> [[1,1],[1,1],[1,1]]
t1.reshape((6,)) # 2个括号,也可以用flatten,输出结果为1维
>>> [1,1,1,1,1,1] # reshape内有几个数就是几维,此处为1维
t1.reshape((1,6))
>>> [[1,1,1,1,1,1]] # reshape内有几个数就是几维,此处为2维
t1.reshape((6,1))
>>> [[1],[1],[1],[1],[1],[1]]
# 统计个数
num = t1.shape[0]*t1.shape[1]
>>> 6
t1.flatten()
>>> [1,1,1,1,1,1] # 1维
数组的运算
inf是infinite无限,nan是空值(两个nan是不相等的)
t1+2
>>> [3,3,3,3,3,3]
0/0 = nan
0.5/0 = inf
t1*t2 # 不是矩阵乘法,对应位置相乘
广播原则
如果两个数组的后缘维度(trailing dimension,即从末尾开始算起的维度]的轴长度相符或其中一方的长度为1,则认为它们是广播兼容的。广播会在缺失和(或)长度为1的维度上进行。
即t5的每一行均减去t7,相乘则是每一行均乘以t7,但长度必须相等
332可以和33也可以和32运算
轴
对于一维数组,只有0轴,二维有0、1轴,三维有0、1、2轴(个人理解n-1轴为行,n轴为列)
np.sum(t1)
np.sum(t1,axis = 0) # 计算列的和,返回列表
t.sum/mean/max/min/std()
np.median/ptp() # 极值
numpy读取数据
间隔、跳过、读取特定、转置
path = './.../....csv'
t1 = np.loadtxt(path, dtype = 'int', delimiter = ',')
t2 = np.loadtxt(path, dtype = 'int', delimiter = ',' unpack = True) # 转置方法1
t2 = t1.T # 转置方法2
t2 = t1.transpose() # 转置方法3
t2 = t1.swapaxes(1,0) # 转置方法4
取特定行
# 虽然返回的值是数字,但是格式是numpy.int64格式
t1[2] # 第三行
t1[2:] # 第三行及以后
t1[[2,8,10]] # 不连续的行
t1[:,2] # 第三列
# 修改值
t1[:,1] = 0 # 根据位置修改值
t1 < 0
>>> [[True False .....]]
t1[t1<10] = 3 # 根据条件修改值,符合条件的数值全部改为3
# 限定区间修改
np.where(t1<10,3,10) # <10赋值3,>10赋值10
t1.clip(3,10)
统计nan的个数/ 哪些为nan
np.count_nonzero(t1!=t1)
>>> 20
np.isnan(t1) # 相当于t1!=t1
>>> [[False, True...]...]
for i in range(t1.shape[1]): # 遍历列
tmp = t1[:,i] # 当前列
if np.count_nonzero(t1!=t)!=0: # 该列有nan
nonan = tmp[tmp==tmp] # ★不为nan的位置的值返回的列表
tmp[np.isnan(tmp)] = nonan.mean() # ★位置为nan的修改为不为nan的均值
数组的拼接
np.vstack((t1,t2)) # 垂直拼接,2个括号
np.hstack((t1,t2)) # 水平拼接,2个括号
t1[[1,2],:] = t1[[2,1],:] # 列的交换
好用的函数
np.zeros/ones/eyes() # eyes对角线
np.argmax(t,axis=0) # 返回位置