numpy的基本用法(一)——基本运算 | | numpy的基本用法(一)——基本运算 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 本文主要是关于numpy的一些基本运算的用法。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169#!/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] 参考资料 https://www.youtube.com/user/MorvanZhou 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏