中文
矩阵
#coding=utf-8
导入Numpy
import numpy as np
数组基础
def test_my_numpy_base():
# 1 创建数组
print "创建数组:"
a = np.array([[1,2,4.0],[3,6,9]])
print a.ndim # 查看行数
print a.shape # 查看数组的维数,返回(n,m), 其中 n 为行数,m 为列数
print a.dtype # 查看元素的类型
# 2 特殊数组
'''
Numpy的特殊数组主要有以下几种:
zeros数组:全零数组,元素全为0;
ones数组:全1数组,元素全为1;
empty数组:空数组,元素全近似为0;
'''
print "特殊数组:"
print np.zeros((2,3), dtype=np.uint8)
print np.ones((3,4), dtype=np.uint8)
print np.empty((3,2), dtype=np.uint8)
# 3 序列数组
print "序列数组:"
print np.arange(1,20,5) #[ 1 6 11 16]
# 4 数组索引
print "数组索引:"
indexArray = np.array([[1,2,4.0],[3,6,9]])
print indexArray[0] #第一项所有
print a[:,1] #所有的项的第二个数
print a[0,2] #第一项第三个数
# 5 数组运算
print "数组运算:"
aCaculate = np.array([1,2,3])
bCaculate = np.array([4,5,6])
print aCaculate
print bCaculate
print "+:", aCaculate+bCaculate
print "-:", aCaculate-bCaculate
print "*:", aCaculate*bCaculate
print "/:", aCaculate/bCaculate
print "**:", aCaculate**bCaculate
print "dot:", np.dot(aCaculate, bCaculate) #点乘相加
print "a max", aCaculate.max()
print "a min", aCaculate.min()
print "a sum", aCaculate.sum()
# 6 数组拷贝
'''
数组的拷贝分为浅拷贝和深拷贝两种,浅拷贝通过数组变量的复制完成,深拷贝使用数组对象的copy方法完成。
'''
print "数组拷贝:"
print "=浅拷贝=" #浅拷贝只拷贝数组的引用,如果对拷贝对象修改。原数组也将修改。
aShallowCopy = np.ones((2,3))
print "Origin a:", aShallowCopy
bShallowCopy = aShallowCopy
print "b the same with a", bShallowCopy
bShallowCopy[1, 2] = 9
print "b Change, and influence a", aShallowCopy
print "=深拷贝=" #深拷贝会复制一份和原数组一样的数组,但他们在内存中是分开存放的,所以改变拷贝数组,原数组不会改变。
aDeepCopy = np.ones((2,3))
bDeepCopy = aDeepCopy.copy()
bDeepCopy[1, 2] = 9
print "just b change"
print "a :", aDeepCopy
print "b :", bDeepCopy
return
#end of test_my_numpy_base
矩阵
def test_my_numpy_matrix():
# 1 创建矩阵
print "创建矩阵:"
A = np.matrix([[1.0,2.0],[3.0,4.0]])
print "A:", A
print type(A) #查看A的类型
# 2 矩阵运算
print "转置:"
print A.T
print "矩阵乘法:"
B = np.matrix([[3.0],[5.0]])
print "B:", B
print "A * B:", A * B
print "逆矩阵:"
print A.I
print "解线性方程组:"
print np.linalg.solve(A, B)
return
#end of test_my_numpy_matrixe