python科学计算基础知识

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
',b
 5 print 'c:
',c
 6 c[0,0]=12;
 7 print 'b
',b
 8 print 'c:
',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.]])

 8、深度复制,对于列表、元组、字典想要复制,需要使用copy模块里deepcopy函数

例如:

import copy as cp
a=[[1,2,3],[4,5,6]];
b=cp.deepcopy(a);
a[1][1]=12;
print a
print b

9、array是元素与元素之间的运算

matrices是服从线性代数运算法则

通过dot来更改运算方式

x=np.ones((2,4));
y=np.ones((4,2));
print np.dot(x,y)

[[ 4.  4.]
 [ 4.  4.]]

array数据类型转换成matrix类型,需要使用Z=asmatrix(A)或Z=mat(A)

a=array([1,2,3]);
a*a

a=np.array([1,2,3]);
a*a

array([1, 4, 9])

10、type、dtype、shape用法

type用来说明数据类型type(A)

dtype是用来指示array数据类型A.dtype

shape用来说明array的大小,A.shape

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