Numpy 数组对象的创建
# numpy创建数组
t1 = np.array([1, 2, 3])
t2 = np.array(range(10))
t3 = np.arange(4, 10, 2)
t4 = np.array([random.random() for i in range(10)])
shape 属性
获取 numpy 数组对象形状
t4.shape # 得到数组形状
reshape 修改 numpy 数组对象形状
t5 = np.arange(0, 24).reshape(4, 6) # 创建0-23的数组并调整为4行6列
dtype 属性
获取 numpy 数组对象数据类型
t1.dtype # 获取数据类型
修改 numpy 数组对象数据类型
t1 = t1.astype("float64") # 修改数据类型为 float
Numpy 数组对象的计算
数组与数的计算
numpy 的广播机制使数和数组的每个元素进行运算。
数组与数组的计算
不同纬度的数组相运算,若从后往前纬度相同则可以运算。
Numpy 数组对象的索引
行列索引
# 行索引
print(t1[0]) # 得到一行
print(t1[1:2]) # :得到连续行
print(t1[[1,3]]) # 得到索引为 1 和 3的行
# 列索引
print(t1[:,1]) # 得到某列
print(t1[:,[1:4]]) # 得到连续列
print(t1[:,[[1,4]])# 得到 1 4 列
bool 索引
t2 = np.arange(0, 24).reshape(4, 6)
print(t2)
print(t2[t2<10])