前言
NumPy 是一个 Python 包。 它代表 “Numeric Python”。 它是一个由多维数组对象和用于处理数组的例程集合组成的库,主要用来处理数组和矩阵。NumPy调用了大量的用C语言编写的算法库,使得其可以直接操作内存,不必进行Python动态语言特性所含有的前期类型检查工作,从而大大提高了运算速度。
这篇文章介绍了numpy最常用的一些用法,敲一遍下面的代码就算入门了。
导入
impotrt numpy as np
向量矩阵
vector = np.array([5, 10, 15, 20]) # 一维向量
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 矩阵
print(matrix)
[[1 2 3]
[4 5 6]
[7 8 9]]
print(matrix.ndim) # 维度
2
print(matrix.shape) # 形状
(3, 3)
print(matrix.size) # 有多少元素
9
print(matrix.dtype) # 向量中的数据类型
int32
切片
vector = np.array([5, 10, 15, 20]) # 一维向量
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 矩阵
print(matrix[0,0]) # >> 5
print(vector[0:3]) # >> [5 10 15] 0~3表示0 1 2
print(matrix[:,1]) # >> [3 5 8] 此处冒号代表所有行
print(matrix[:,0:2]) # >> [[1 2], [4 5], [7 8]]
判断操作
vector = np.array([5, 10, 15, 20]) # 一维向量
print(vector == 10)
(