python numpy 使用笔记 矩阵操作

(原创文章转载请标注来源)

在学习机器学习的过程中经常会用到矩阵,那么使用numpy扩展包将是不二的选择

建议在平Python中用多维数组(array)代替矩阵(matrix)

入门请考 http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#

import numpy np

1. 读写数组,这里可以看成矩阵

#返回值格式(评分,信任表,用户个数,项目个数)
   a = np.arange(0,12,0.5).reshape(4,-1)
   np.savetxt("a.txt", a) # 缺省按照'%.18e'格式保存数据,以空格分隔
   np.loadtxt("a.txt")
   np.loadtxt('a.txt',dtype='int')#设置读出的数据类型

 

2. 使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变:

a = np.arange(4).reshape(2,2)
b = np.arange(6).reshape(2,3)
print('the result is\n ',a)
print('the result is\n ',b)

 

3.transpose()对数组进行转置

print('the transpose is\n ',b.transpose())#转置

 

4. 矩阵运算

np.dot() #矩阵的乘法
print('the result is\n ',np.dot(a,b))#矩阵乘
np.linalg.inv() #求矩阵的逆
print('the inverse is\n ',np.linalg.inv(a))#逆矩阵

 

5. 求行列大小

(m,n) = a.shape#求行列个数

 

6. 求最值

temp1 = np.max(a[:,0])
temp2 = np.min(a[:,0])

 

7. 求第三列等于1的个数

np.sum(a[:,2]==1)



8.
求一组随机数组

randIndices = np.random.permutation(4)

ans=array[[3,0,2,1]]

9. 组合两个数组

np.vstack((a,b))#纵向结合,保证列数相同 注意双括号
np.hstack((a,b))#横向结合,保证行数相同

 

10. 求和 和 计算平均数

 

np.sum(a,0)#0代表求得是各列的和

np.mean(a,1)#1代表求得各行的平均数

  

11.求交集

np.intersectld(a[0,:],b[0,:])#求两个一维数组的交集

 

12.条件查询

np.where(a>5)#找到所有满足条件的位置

np.where(a>5,0,1)#找到这些值满足赋值为0,不满足赋值为1

 

13.矩阵写文件 追加 方式

fileObject = open('result.txt','a')#追加的方式打开文件
a = [[1,2,3] ,[3,4,5] , [4,5,6]]#存取list
for i in a:
  tmp = str(i)
  tmp = tmp.replace('[','')
  tmp = tmp.replace('[','')+'\n'
  fileObject.weite(tmp)
fileObject.close()
b = np.loadtxt('result.txt',delimiter=',')#同样可以读出矩阵
print(b[:,:]) 

 

未完。。补充中。。欢迎讨论

 

posted @ 2016-04-14 21:39  Scott_Zhang  阅读(11104)  评论(0编辑  收藏  举报