numpy的基本用法(一)——基本运算

来源:互联网 发布:关闭数据库的命令 编辑:程序博客网 时间:2024/06/16 05:47

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是关于numpy的一些基本运算的用法。

#!/usr/bin/env python# _*_ coding: utf-8 _*_import numpy as np# Test 1# 定义矩阵arr = np.array([[1, 2, 3],                [4, 5, 6]])print arr# Test 1 Result[[1 2 3] [4 5 6]]# Test 2# 矩阵的维度print 'number of dim: ', arr.ndim# 矩阵的shape,即每一维度上的元素个数print 'shape: ', arr.shape# 矩阵的元素总数print 'size: ', arr.size# 矩阵的元素类型print 'dtype: ', arr.dtype# Test 2 Resultnumber of dim:  2shape:  (2, 3)size:  6dtype:  int64# Test 3# 定义矩阵及矩阵的元素类型——int32, int64, float32, float64a = np.array([1, 2, 3], dtype = np.int32)print aprint a.ndimprint a.shapeprint a.sizeprint a.dtype# Test 3 Result[1 2 3]1(3,)3int32# Test 4# 定义零矩阵z = np.zeros((3, 4), dtype = np.int16)print zprint z.dtype# 定义空矩阵n = np.empty((3, 4))print n# Test 4 Result[[0 0 0 0] [0 0 0 0] [0 0 0 0]]int16[[ 0.  0.  0.  0.] [ 0.  0.  0.  0.] [ 0.  0.  0.  0.]]# Test 5# 定义向量, 10-20之间, 元素间隔为2, 左闭右开a = np.arange(10, 20, 2)print a# 定义向量并转为矩阵b = np.arange(12).reshape((3, 4))print b# 定义向量, 类型是线性间隔a = np.linspace(1, 10, 6).reshape((2, 3))print a# Test 5 Result[10 12 14 16 18][[ 0  1  2  3] [ 4  5  6  7] [ 8  9 10 11]][[  1.    2.8   4.6] [  6.4   8.2  10. ]]# Test 6# 矩阵的加、减、点乘、平方a = np.array([10, 20, 30, 40])b = np.arange(4)c = a - bd = a + bprint a, bprint c, de = a * bprint ef = e ** 2print f# Test 6 Result[10 20 30 40] [0 1 2 3][10 19 28 37] [10 21 32 43][  0  20  60 120][    0   400  3600 14400]# Test 7# 矩阵的三角运算——sin, cos, tansin = 10 * np.sin(a)print sin# 矩阵的判断print b < 3print b == 3# Test 7 Result[-5.44021111  9.12945251 -9.88031624  7.4511316 ][ True  True  True False][False False False  True]# Test 8# 矩阵的点乘及乘法a = [ [1, 1], [0, 1]]b = np.arange(4).reshape((2, 2))c = a * bd = np.dot(a, b)print cprint d# Test 8 Result[[0 1] [0 3]][[2 4] [2 3]]# Test 9# np.random返回随机的浮点数,在半开区间 [0.0, 1.0)# 定义随机矩阵a = np.random.random((2, 4))print a# Test 9 Result[[ 0.93213483  0.58102186  0.98259187  0.27387014] [ 0.43796835  0.98195976  0.29343791  0.94752226]]# Test 10# 矩阵的求和, 最小值, 最大值print np.sum(a)print np.min(a)print np.max(a)# 矩阵某一维度的求和, 最小值, 最大值, 0是列, 1是行print np.sum(a, axis = 1)print np.max(a, axis = 1)print np.min(a, axis = 0)# Test 10 Result5.430506974850.2738701402820.982591870104[ 2.7696187   2.66088828][ 0.98259187  0.98195976][ 0.43796835  0.58102186  0.29343791  0.27387014]
0 0
原创粉丝点击