Numpy学习笔记

Numpy(Numerical Python的简称)高性能科学计算和数据分析的基础包。其部分功能如下:

  • ndarray,具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组。
  • 数组运算,不用编写循环
  • 可以读写磁盘数据,操作内存映射
  • 线性代数
  • 集成c,c++等语言

python能够包装c、c++以numpy数组形式的数据。pandas提供了结构化或表格化数据的处理高级接口,

还提供了numpy不具备的时间序列处理等;


1 创建ndarray
ndarray多维数组,要求所有元素的类型一致,通常说的“数组”、“Numpy数组”、“ndarray”都是指“ndarray”对象。

In [1]: import numpy as np

In [2]: np.arange(10)//创建从0到9的包含10个元素的一维数组
Out[2]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: np.array([1,2,3,4,5])//输入数据转换为ndarray对象,可以是python元组、列表或其他序列类型。可以自动识别dtype,或者手动指定类型
Out[3]: array([1, 2, 3, 4, 5])

In [4]: np.ones((2,3))//包含2个数组对象的数组,每个数组对象里包含3个都为1.0的元素
Out [4]: array([[ 1.,  1.,  1.],
			   [ 1.,  1.,  1.]])

In [5]: np.ones_like([1,2,3,4,5])//返回一个用1填充的跟输入 形状和类型 一致的数组
Out[5]: array([1, 1, 1, 1, 1])			   
			   
In [6]: np.zeros((2,5))//包含2个数组对象的数组,每个数组对象里包含5个都为0.0的元素
Out[6]: array([[ 0.,  0.,  0.,  0.,  0.],
               [ 0.,  0.,  0.,  0.,  0.]])
			   
In [7]: np.zeros_like((2,5))//返回一个用0填充的跟输入 形状和类型 一致的数组
Out[7]: array([0, 0])

In [8]: np.eye(2)//创建一个2*2的单位矩阵(阵列)
Out[8]: array([[ 1.,  0.],
               [ 0.,  1.]])
			
In [9]: np.identity(2)//创建一个2*2的单位矩阵(阵列)
Out[9]: array([[ 1.,  0.],
               [ 0.,  1.]])

In [10]: np.empty((2,3))//包含2个数组对象的数组,每个数组对象里包含3个都为空的元素,全空数组,只分配内存空间,不填充任何值
Out[10]: array([[ 0.,  0.,  0.],
			   [ 0.,  0.,  0.]])
			   
In [11]: np.empty((3,3))//包含3个数组对象的数组,每个数组对象里包含3个都为空的元素,全空数组,只分配内存空间,不填充任何值
Out[11]: array([[  1.77010735e-290,   1.77018564e-290,   1.77026392e-290],
                [  1.77034221e-290,   1.77042050e-290,   7.77725110e-071],
                [  7.40790129e-038,   4.70504460e-086,   5.89204343e+294]])
				
In [12]: np.empty((3,4))//包含3个数组对象的数组,每个数组对象里包含4个都为空的元素,全空数组,只分配内存空间,不填充任何值
Out[12]: array([[  3.31023983e-322,   0.00000000e+000,   0.00000000e+000,0.00000000e+000],
                [  0.00000000e+000,   0.00000000e+000,   0.00000000e+000,0.00000000e+000],
                [  0.00000000e+000,   0.00000000e+000,   0.00000000e+000,0.00000000e+000]])


2 ndarray数据类型
当需要控制数据在内存和磁盘中的存储方式时,尤其是大数据集,就需要了解如何控制存储类型。
dtype的表示形式有几种:
类型列中的值,使用字符串方式:如“int8”;
类型列中的值,使用如np.int8表示;
类型代码列中的值,使用字符串表示,如“f2”;

下表是所有支持的类型和说明:

也可以使用astype修改dtype

在格式转换过程中:

  • 浮点数转换成整数,浮点数小数部分会被去掉;
  • 如果字符串格式的数字,可以转换为数值形式;
  • 复数转换
In [13]: a = np.array([1,2,3],dtype="int32")//指定数组类型为int32
In [13]: a.dtype
Out[13]: dtype('int32')

In [14]: b = np.array([1,3,3],dtype=np.float32)//指定数组类型为float64
In [14]: b.dtype
Out[14]: dtype('float32')				
				
In [15]: c = a.astype("float64")//把a数组类型由int32转换成float64
In [15]: c.dtype
Out[15]: dtype('float32')

In [16]: vector = np.array([5,10,15,20])//把传入的结构转换成ndarray对象
		 matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
		 print vector
		 print matrix				
Out[16]: [ 5 10 15 20]
		 [[ 5 10 15]
		  [20 25 30]
		  [35 40 45]]				
				
In [17]: print vector.shape//查看数组的结构
		 print matrix.shape				
Out[17]: (4,)//一维数组包含4个元素
         (3, 3)	//三维数组,每个包含3个元素			
				
In [18]: numbers = np.array([1,2,3,4])//转换成ndarray后数据类型变成一致
         print numbers
         print numbers.dtype				
Out[18]: [1 2 3 4]
         int32			
				
In [19]: numbers = np.array([1,2,3,4.0])//转换成ndarray后数据类型变成float64
         print numbers
         print numbers.dtype				
Out[19]: [ 1.  2.  3.  4.]
         float64				
				
In [20]: numbers = np.array([1,2,3,"4"])//转换成ndarray后数据类型变成|S11
         print numbers
         print numbers.dtype				
Out[20]: ['1' '2' '3' '4']
         |S11				
			
		 //从文件读取数据,数据每一行的分隔符为",",以字符串的形式读取,跳过前面的一行	
In [21]: world_alcoho = np.genfromtxt("world_alcohol.txt",delimiter = ",",dtype = str,skip_header = 1)
         print world_alcoho				
Out[21]: [['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
          ['1986' 'Americas' 'Uruguay' 'Other' '0.5']
          ['1985' 'Africa' "Cte d'Ivoire" 'Wine' '1.62']
          ..., 
          ['1987' 'Africa' 'Malawi' 'Other' '0.75']
          ['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
          ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]				

		 //切片取值,索引从0开始,取第1行第4列的元素	
In [22]: uruguay_other_1986 = world_alcoho[1,4]
         third_country = world_alcoho[2,2]//取第2行第2列的元素
		 print uruguay_other_1986
         print third_country
Out[22]: 0.5
         Cte d'Ivoire
	
In [23]: vector = np.array([10,20,30,40,50])
         print vector[1:3]//从索引1开始取到索引3但不包括3,左闭右开的区间
Out[23]: [20 30]

In [24]: matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
         print matrix
         print "--------------"
         print matrix[:,1]//:表示取所有行,1:表示取第一列
Out[24]: [[ 5 10 15]
          [20 25 30]
          [35 40 45]]
         --------------
         [10 25 40]

In [25]: print matrix[:,0:2]//:表示取所有行,0:2表示取第0列和第1列
Out[25]: [[ 5 10]
          [20 25]
          [35 40]]

In [26]: vector = np.array([10,20,30,40,50])
         vector == 10  //判断数组中有没有等于10的
Out[26]: array([ True, False, False, False, False], dtype=bool)

         //判断矩阵中有没有等于25的
In [27]: matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
         print matrix
         print "--------------"
         matrix == 25
Out[27]: [[ 5 10 15]
          [20 25 30]
          [35 40 45]]
         --------------
         [[False False False]
          [False  True False]
          [False False False]]
        
		//通过布尔值作为索引反过来取值
In [28]: vector = np.array([10,20,30,40,50])
         equal_to_ten = (vector == 10)
         print equal_to_ten
         print vector[equal_to_ten]
Out[28]: [ True False False False False]
         [10]

		//通过布尔值作为索引反过来取值
In [29]: matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
         second_column_25 = (matrix[:,1]==25)//第一列等于25的
         print matrix
         print "--------------"
		 print second_column_25
		 print "--------------"
         print matrix[second_column_25,:]//25所在的一行
Out[29]: [[ 5 10 15]
          [20 25 30]
          [35 40 45]]
         --------------
         [False  True False]
         --------------
         [[20 25 30]]

		//与操作
In [30]: vector = np.array([10,20,30,40,50])
         equal_to_ten_and_five = (vector == 10) & (vector ==5)
         print equal_to_ten_and_five
Out[30]: [False False False False False]

		//或操作
In [31]: vector = np.array([10,20,30,40,50])
         equal_to_ten_and_five = (vector == 10) | (vector ==50)
         print equal_to_ten_and_five
Out[31]: [True False False False True]

		//类型转换
In [32]: vector = np.array(["1","2","3"])
         print vector
         print vector.dtype
         vector = vector.astype(float)//转换成float类型
         print vector
         print vector.dtype
Out[32]: ['1' '2' '3']
         |S1
         [ 1.  2.  3.]
         float64

		//获取最大值和最小值
In [33]: vector = np.array([10,20,30,40,50])
         print vector.min()
         print vector.max()
         print(help(np.array))//查看帮助文档
Out[33]: 10
         50

		//按维度求和
In [34]: matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
         print matrix
         print "--------------"
         print matrix.sum(axis=1)//按行求和
Out[34]: [[ 5 10 15]
          [20 25 30]
          [35 40 45]]
         --------------
         [ 30  75 120]

		//按维度求和
In [35]: matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
         print matrix
         print "--------------"
         print matrix.sum(axis=0)//按列求和
Out[35]: [[ 5 10 15]
          [20 25 30]
          [35 40 45]]
         --------------
         [60 75 90]


2017-10-18 22:11

		//数组的变换
In [36]: a = np.arange(15)
         print a
         print "--------------"
         print a.reshape(3,5)//把a数组变换成3行5列的矩阵
		 print "--------------"
         b = a.reshape(3,5)
         print b.shape//打印b矩阵的结构
		 print "--------------"
         print b.ndim//打印b矩阵的维度
         print "--------------"
         print b.dtype.name//打印b矩阵的数据类型
         print "--------------"
         print b.size//打印b矩阵的元素个数
Out[36]: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
         --------------
         [[ 0  1  2  3  4]
          [ 5  6  7  8  9]
          [10 11 12 13 14]]
         --------------
         (3, 5)
         --------------
         2
         --------------
         int32
         --------------
         15

		 //构造全0和全1矩阵
In [37]: a = np.zeros((3,4))//3行4列的全0矩阵
         print a
         b = np.ones((3,4),dtype = np.int32)//3行4列的全1矩阵
         print "--------------"
         print b
Out[37]: [[ 0.  0.  0.  0.]
          [ 0.  0.  0.  0.]
          [ 0.  0.  0.  0.]]
         --------------
         [[1 1 1 1]
          [1 1 1 1]
          [1 1 1 1]]

		 //构造等差数组
In [38]: a = np.arange(10,30,5)//10到30(不包括30)的等差为5的数组
         print a
Out[38]: [10 15 20 25]

		 //构造随机数矩阵
In [39]: a = np.random.random((2,3))//2行3列的随机数矩阵
         print a
Out[39]: [[ 0.37568206  0.73577444  0.75831937]
          [ 0.50737538  0.04136392  0.18015326]]

		 //构造等差数组
In [40]: from numpy import pi
         a = np.linspace(0,2*pi,10)//0到2*Pi之间10个数的等差数列
         print a
Out[40]: [ 0.          0.6981317   1.3962634   2.0943951   2.7925268   3.4906585
           4.1887902   4.88692191  5.58505361  6.28318531]

		//数组运算
In [41]: a = np.array([20,30,40,50])
         b = np.arange(4)
         print a
         print "--------------"
         print b
         print "--------------"
         c = a - b
         print c
         print "--------------"
         print b**2//求平方
         print "--------------"
         print a<35
Out[41]: [20 30 40 50]
         --------------
         [0 1 2 3]
         --------------
         [20 29 38 47]
         --------------
         [0 1 4 9]
         --------------
         [ True  True False False]

		//矩阵运算
In [42]: A = np.array([[1,1],[0,1]])
         B = np.array([[2,0],[3,4]])
         print A
         print "--------------"
         print B
         print "--------------"
         C = a * b//对应位置相乘
         print C
         print "--------------"
         print A.dot(B)//矩阵相乘
         print "--------------"
         print np.dot(A,B)//矩阵相乘
Out[42]: [[1 1]
          [0 1]]
         --------------
         [[2 0]
          [3 4]]
         --------------
         [  0  30  80 150]
         --------------
         [[5 4]
          [3 4]]
         --------------
         [[5 4]
          [3 4]]

		//矩阵变换
In [43]: a = np.floor(10*np.random.random((3,4)))//随机生成3行4列的矩阵,每个数向下取整
         print a
         print "--------------"
         print a.ravel()//把矩阵变成向量
         print "--------------"
         a.shape = (6,2)//变换成6行2列的矩阵
         print a
         print "--------------"
         print a.T//矩阵的转置
		 print "--------------"
         print a.reshape(3,-1)//根据a中的元素个数自动计算-1的真实值
Out[43]: [[ 8.  9.  1.  9.]
          [ 3.  9.  0.  0.]
          [ 3.  6.  1.  1.]]
         --------------
         [ 8.  9.  1.  9.  3.  9.  0.  0.  3.  6.  1.  1.]
         --------------
         [[ 8.  9.]
          [ 1.  9.]
          [ 3.  9.]
          [ 0.  0.]
          [ 3.  6.]
          [ 1.  1.]]
         --------------
         [[ 8.  1.  3.  0.  3.  1.]
          [ 9.  9.  9.  0.  6.  1.]]
         --------------
         [[ 8.  9.  1.  9.]
          [ 3.  9.  0.  0.]
          [ 3.  6.  1.  1.]]

		//矩阵合并
In [44]: a = np.floor(10*np.random.random((2,2)))
         b = np.floor(10*np.random.random((2,2)))
         print a
         print "--------------"
         print b
         print "--------------"
         print np.hstack((a,b))//横向合并
         print "--------------"
         print np.vstack((a,b))//纵向合并
Out[44]: [[ 1.  2.]
          [ 6.  8.]]
         --------------
         [[ 5.  0.]
          [ 4.  2.]]
         --------------
         [[ 1.  2.  5.  0.]
          [ 6.  8.  4.  2.]]
         --------------
         [[ 1.  2.]
          [ 6.  8.]
          [ 5.  0.]
          [ 4.  2.]]

		//矩阵切分
In [45]: a = np.floor(10*np.random.random((2,12)))
         print a
         print "--------------"
         print np.hsplit(a,3)//把a矩阵横向平均切分成3份
         print "--------------"
         print np.hsplit(a,(3,4))把a矩阵在3的位置切一次,在4的位置切一次
         print "--------------"
         a = np.floor(10*np.random.random((12,2)))
         print np.vsplit(a,3)//把a矩阵纵向平均切分成3份
Out[45]: [[ 0.  3.  8.  8.  4.  9.  1.  9.  5.  9.  6.  7.]
          [ 0.  1.  6.  1.  0.  4.  0.  9.  9.  5.  8.  1.]]
         --------------
         [array([[ 0.,  3.,  8.,  8.],
                [ 0.,  1.,  6.,  1.]]), array([[ 4.,  9.,  1.,  9.],
                [ 0.,  4.,  0.,  9.]]), array([[ 5.,  9.,  6.,  7.],
                [ 9.,  5.,  8.,  1.]])]
         --------------
         [array([[ 0.,  3.,  8.],
                [ 0.,  1.,  6.]]), array([[ 8.],
                [ 1.]]), array([[ 4.,  9.,  1.,  9.,  5.,  9.,  6.,  7.],
                [ 0.,  4.,  0.,  9.,  9.,  5.,  8.,  1.]])]
         --------------
         [array([[ 1.,  6.],
                 [ 6.,  7.],
                 [ 5.,  9.],
                 [ 0.,  3.]]), array([[ 8.,  3.],
                 [ 5.,  1.],
                 [ 7.,  1.],
                 [ 3.,  8.]]), array([[ 2.,  7.],
                 [ 4.,  9.],
                 [ 4.,  4.],
                 [ 0.,  3.]])]

		//矩阵复制
In [46]: a = np.arange(12)
         b = a
         print b is a
         print "--------------"
         b.shape = 3,4
         print a.shape
         print "--------------"
         print id(a)
         print "--------------"
         print id(b)
Out[46]: True
         --------------
         (3, 4)
         --------------
         69083208
         --------------
         69083208

		//矩阵浅复制
In [47]: c = a.view()
         print c is a
         print "--------------"
         print id(c)
         print "--------------"
         print id(a)
         print "--------------"
         c.shape = 2,6
         print c.shape
         print "--------------"
         print a.shape
         print "--------------"
         c[0,4] = 1234
         print a
		 print "--------------"
         print id(c)
         print "--------------"
         print id(a)
Out[47]: False
         --------------
         69084728
         --------------
         69083208
         --------------
         (2, 6)
         --------------
         (3, 4)
         --------------
         [[   0    1    2    3]
          [1234    5    6    7]
          [   8    9   10   11]]
         --------------
         69084768
         --------------
         69083208

		//矩阵深复制
In [48]: d = a.copy()
         print a
         print "--------------"
         print d is a
         print "--------------"
         d[0,0] = 9999
         print d
         print "--------------"
         print id(d)
         print "--------------"
         print id(a)
Out[48]: [[   0    1    2    3]
          [1234    5    6    7]
          [   8    9   10   11]]
         --------------
         False
         --------------
         [[9999    1    2    3]
          [1234    5    6    7]
          [   8    9   10   11]]
         --------------
         69074720
         --------------
         69083208

		//根据索引操作数据
In [49]: data = np.sin(np.arange(20)).reshape(5,4)
         print data
         ind = data.argmax(axis=0)//查找每一列的最大数并返回索引
         print ind
         data_max = data[ind,range(data.shape[1])]//根据索引查找对应的数据
         print data_max
Out[49]: [[ 0.          0.84147098  0.90929743  0.14112001]
          [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
          [ 0.98935825  0.41211849 -0.54402111 -0.99999021]
          [-0.53657292  0.42016704  0.99060736  0.65028784]
          [-0.28790332 -0.96139749 -0.75098725  0.14987721]]
         --------------
         [2 0 3 1]
         --------------
         [ 0.98935825  0.84147098  0.99060736  0.6569866 ]

		//数组的扩展
In [50]: a = np.arange(0,40,10)
         print a
         print "--------------"
         b = np.tile(a,(2,3))//行扩展为原来的2倍,列扩展为原来的3倍
         print b
         print "--------------"
         b = np.tile(a,(3,2))//行扩展为原来的3倍,列扩展为原来的2倍
         print b
Out[50]: [ 0 10 20 30]
         --------------
         [[ 0 10 20 30  0 10 20 30  0 10 20 30]
          [ 0 10 20 30  0 10 20 30  0 10 20 30]]
         --------------
         [[ 0 10 20 30  0 10 20 30]
          [ 0 10 20 30  0 10 20 30]
          [ 0 10 20 30  0 10 20 30]]

		//数组的排序
In [51]: a = np.array([[4,3,5],[1,2,1]])
         print a
         print "--------------"
         b = np.sort(a,axis=1)//按行排序
         print b
         print "--------------"
         a = np.array([4,3,1,2])
         j = np.argsort(a)//数据排序后的索引
         print j
         print "--------------"
         print a[j]
Out[51]: [[4 3 5]
          [1 2 1]]
         --------------
         [[3 4 5]
          [1 1 2]]
         --------------
         [2 3 1 0]
         --------------
         [1 2 3 4]


猜你喜欢

转载自blog.csdn.net/u012592062/article/details/78254919
今日推荐