根据条件筛选行(筛选)
筛选矩阵中第7列值为5的行
B = A[ A[:,6] == 5]
筛选矩阵中第7列大于5的行
B = A[ A[:,6] > 5]
Numpy基础操作
根据行列号取值(查询)
取第2行第2列的数字
import numpy as np
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y=x[1,1]
print(y)
截取前几行前几列
import numpy as np
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y=x[:2]
print(y)
z=x[:,:2]
print(z)
截取某几行某几列
import numpy as np
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y=x[1,1:3]
根据值求行列号(定位)
输出某行最大值所在的列索引
import numpy as np
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y = np.argmax(x, 1)
print(y)
输出某列最大值所在的行索引
y = np.argmax(x, 0)
print(y)
最大值所在行列号
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y = np.where(x == np.max(x))
print(y)
print("最大值所在行:",y[0],"最大值所在列:",y[1])
按行/列求和(求和)
按行求和,将和添加到矩阵最后一列
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y = np.sum(x, axis=1)
print(y)
xy = np.hstack((x, y.reshape(x.shape[0], -1)))
print(xy)
按列求和,将和添加到矩阵最后一行
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
z = np.sum(x, axis=0)
print(z)
xz = np.vstack((x, z))
print(xz)
赋值
按条件赋值
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
x[x<=5]=0
print(x)
where()
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
y = np.where(x>5,x,0)
print(y)
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
print(x>5)
给指定 行 / 列 / [行,列] 赋值
x=np.arange(0,12)
x=x.reshape((3,4))
print(x)
x[1,1] = 999
print(x)
x[1] = 123
print(x)
x[:,1] = 321
print(x)