码迷,mamicode.com
首页 > 编程语言 > 详细

python科学计算基础知识

时间:2016-04-12 22:20:42      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

1、导入基本函数库

import numpy as np

 

2、获取矩阵元素字节数

1 a=np.array([1,2,3],dtype=np.float32)
2 a.itemsize
output: 4

3、获取数组维数A.shape

例如

1 a=np.array([[1,2,3],[4,5,6]]);
2 
3 a.shape
4 
5 output:(2,3)

4、选取某一行或某一列元素,

注意numpy中数组起始坐标是0开始的,跟matlab中有区别。matlab中是从1开始的。

python中列表[start,end,step],有开始数、终止数、步长;而matlab中是[start:step:end]。

 

a[:,0],选取第一列

a[0,:],选取第一行

5、numpy中数组赋值时,如果没有超过原始数组维数时,只将引用赋值,而不是复制赋值。

如果想要进行复制,需要使用函数B=A.copy(),与matlab有区别例如:

 1 import numpy as np
 2 b=np.ones((3,3))
 3 c=b;
 4 print b\n,b
 5 print c:\n,c
 6 c[0,0]=12;
 7 print b\n,b
 8 print c:\n,c
 9 
10 b
11 [[ 1.  1.  1.]
12  [ 1.  1.  1.]
13  [ 1.  1.  1.]]
14 c:
15 [[ 1.  1.  1.]
16  [ 1.  1.  1.]
17  [ 1.  1.  1.]]
18 b
19 [[ 12.   1.   1.]
20  [  1.   1.   1.]
21  [  1.   1.   1.]]
22 c:
23 [[ 12.   1.   1.]
24  [  1.   1.   1.]
25  [  1.   1.   1.]]

6、 2维矩阵matrix,python中matrix只能是二维的。

简单应用,矩阵乘

1 a=np.matrix([[1,2,3],[4,5,6],[7,8,9]]);
2 b=np.matrix([[1],[0],[0]]);
3 a*b
4 matrix([[1],
5         [4],
6         [7]])

也可以使用数组点积表示:

1 A=np.array([[1,2,3],[4,5,6],[7,8,9]])
2 x=np.array([[1],[0],[0]])
3 A.dot(x)
4 array([[1],
5        [4],
6        [7]])

7、当需要将数组转换成矩阵时,要使用np.matrix(A)

例如

1 a=np.ones((3,3));
2 
3 b=np.ones((3,1));
4
5 np.matrix(a)*b
6 
7 matrix([[ 3.],
8         [ 3.],
9         [ 3.]])

 

python科学计算基础知识

标签:

原文地址:http://www.cnblogs.com/zhaopengcheng/p/5384539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!