python_numpy,简要操作

来源:互联网 发布:移动软件开发是什么 编辑:程序博客网 时间:2024/06/06 01:35

参考:https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

1.背景:numpy是python下的科学计算包,常用的是其数组numpy.ndarray

>>>a= numpy.arange(30).reshape(10,3)

>>>type(a)

<type 'numpy.ndarray'>

2.创建数组

2.1 实验创建 

a= numpy.arange(30).reshape(10,3)  #reshape调整数组的行列数

2.2 从list创建

>>> b=[1,2,3,4,5]
>>> a= numpy.array(b) 

>>> a

array([1, 2, 3, 4, 5])

2.3 ndarray与list的转化

list转ndarray见2.2

ndarray转list:ndarrayobjects.tolist()

3.数组常用操作:

假如,数组a的内容为

>>>a= numpy.arange(30).reshape(10,3)

>>> a
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26],
       [27, 28, 29]])

3.1 提取数组2~3行

>>> a[2:4]
array([[ 6,  7,  8],
       [ 9, 10, 11]])

3.2 提取数组的2~3列

>>> a[:,1:3]
array([[ 1,  2],
       [ 4,  5],
       [ 7,  8],
       [10, 11],
       [13, 14],
       [16, 17],
       [19, 20],
       [22, 23],
       [25, 26],
       [28, 29]])

3.3 提取出数组除最后一列的所有列

>>> a[:,:-1] 
array([[ 0,  1],
       [ 3,  4],
       [ 6,  7],
       [ 9, 10],
       [12, 13],
       [15, 16],
       [18, 19],
       [21, 22],
       [24, 25],
       [27, 28]])

4.常用函数

数组行列数:a.shape #(10, 3)

按照行或者列加和

>>> a.sum(axis=0)  
array([135, 145, 155])

>>> a.sum(axis=1)  
array([ 3, 12, 21, 30, 39, 48, 57, 66, 75, 84])

5.在矩阵中插入列 http://www.tuicool.com/articles/ZVrUjq3

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

b = np.ones(3)

np.insert(a,0, values=b, axis=1)

array([[1,1, 2, 3],[1, 4, 5, 6], [1,7, 8, 9]])

np.insert(a,3, values=b, axis=1)

array([[1,2, 3, 1],[4, 5, 6, 1], [7,8, 9, 1]])


0 0
原创粉丝点击