作用:
python用来做科学计算的模块
安装使用pip3即可
导入和读取文件 使用genfromtxt
import numpy as np #导入并重命名为np
world_alcohol = np.genfromtxt('world_alcohol.txt', delimiter=',', dtype='str', skip_header=1) #genfromtxt 读取文件的函数
print(type(world_alcohol)) #输出数据的类型
print(world_alcohol) #打印出读取到的数据
array用来创造一个数组
import numpy
vector = numpy.array([1, 2, 3, 4])
matrix = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix3 = numpy.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
print(vector)
print(matrix)
print(matrix3)
ndim 显示它的维度
a.ndim
shape用来显示它的维度大小的元组,返回的是一个元组。 如果是一个向量的话,那么将显示向量的长度
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)
dtype 显示它的类型,必须是统一的,如果有一个float的类型 那么它将所有的元素都会转化成float
numbers = numpy.array([1, 2, 3, 4.0])
numbers.dtype
一个ndarray,如果说相找出其中的数据是否与另外一个数字是否与另一个数字相等 那直接==就好了 得到的就是布尔值的矩阵
然后将布尔值的矩阵,作为下标就可以得到一个与该数相等的矩阵
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
bool1 = matrix == 25
print(matrix[bool1])
astype:转换数组的数据类型。
int32 --> float64 完全ojbk
float64 --> int32 会将小数部分截断
string_ --> float64 如果字符串数组表示的全是数字,也可以用astype转化为数值类型
vector = numpy.array(["1", "2", "3"])
print (vector.dtype)
print (vector)
vector = vector.astype(float)
print (vector.dtype)
print (vector)
zeros生成一个全零矩阵
numpy.zeros ((3,4)) #生成一个三行四列的全零矩阵
arange 生成一个连续矩阵
numpy.arange(10,30,2)#起点终点步长
random 生成一个随机矩阵
np.random.random((2,3))
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
在指定的间隔内返回均匀间隔的数字。
返回num均匀分布的样本,在[start, stop]。
这个区间的端点可以任意的被排除在外。
np.linspace( 0, 2*pi, 100 )
矩阵乘法 点乘
a = np.array([[1,1],
[0,1]])
b = np.array([[2,0],
[3,4]])
print(a.dot(b))
print(numpy.dot(a,b))
floor元素向下取整 random指定维度
a = np.floor(10*np.random.random((3,4)))
#随机取值然后乘10 并向下取值
矩阵元素开根号sqrt
矩阵元素的幂运算
import numpy as np
B = np.arange(3)
print B
#print np.exp(B)
print np.sqrt(B)
矩阵拼接
numpy.vstack():在竖直方向上堆叠
numpy.hstack():在水平方向上平铺
arr1=numpy.array([1,2,3])
arr2=numpy.array([4,5,6])
矩阵切分
numpy.hsplit(a,3) #按行来
numpy.vsplit(a,3) #按列来
矩阵的拷贝 copy
d = a.copy()
d is a
d[0,0] = 9999
print (b)
print (a)
矩阵的排序
a = np.array([[4, 3, 5], [1, 2, 1]])
#print a
#b = np.sort(a, axis=1) #按行排序
#print b
#b
#a.sort(axis=1) #按行排序
#print a
a = np.array([4, 3, 1, 2])
j = np.argsort(a) #大小顺序的索引
print j
print a[j]
扩展矩阵 使用tile将它扩展 将每个a矩阵作为一个元素扩展为 三行五列
a = np.arange(0, 40, 10)
b = np.tile(a, (3, 5))
print b