1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 软件技术部python培训

软件技术部python培训

时间:2020-04-22 15:19:32

相关推荐

软件技术部python培训

软件技术部python培训

1.变量1.1变量的定义1.2查看变量的类型2.输出2.1简单的使用输出函数2.2格式化输出3.输入3.1input()函数3.2转换数据类型4.运算符4.1与C语言不同的基本运算符4.2赋值运算符4.3复合赋值运算符4.4比较运算符4.5逻辑运算符5.if语句5.1语法5.2加上else5.3多重判断5.4if的嵌套5.5三目运算符6循环6.1while循环6.2用while循环实现1到100的累加6.3break6.4continue6.5循环的嵌套6.6while else语句6.7for循环7.字符串7.1定义字符串7.2索引7.3切片7.4字符串一些常用的操作方法8列表8.1定义列表8.2列表常用的一些操作9.元组9.1定义元组9.2元组常见的操作10.字典10.1定义字典10.2字典常用的操作11.集合13.1定义集合13.2集合常用的操作14.一些公用的操作14.1合并14.2复制14.3求最大最小值14.4容器类型的转换15.函数初识16.库的调用17.time库18.jieba库19.numpy库1.ndarray数组基础1)数组的创建及使用2)特殊数组3)数组索引4)数组运算5)数组的拷贝6)numpy降维2.矩阵1)创建矩阵2)矩阵运算3.Numpy线性代数相关函数20.NumPy Matplotlib绘制正弦波subplot()bar()plt()tick能见度设置散点图条形图contour等高线图image图片显示3D数据图图中图主次坐标轴Animation动画

1.变量

1.1变量的定义

#python中常见的变量a = 1 #整型b = 1.0 #浮点型c = 'esta' #字符串d = True #布尔类型

1.2查看变量的类型

#type()函数可以返回变量的类型print(type(a))print(type(b))print(type(c))print(type(d))

2.输出

2.1简单的使用输出函数

#直接向print()函数中传入想要输出的变量或常量print("hello world")temp = 233print(temp)

2.2格式化输出

age = 20 name = 'abcd'weight = 66.66student_id = 1962654155788print("我今年%d岁了" % age)print("我的体重是%f斤" %weight)print("我的体重是%.2f斤" %weight)print("我叫%s,我今年%d岁了" % (name, age))print(f"我叫{name},我今年{age}岁了,我的体重是{weight}")#f-格式化字符串是Python3.6中新增的格式化方法print('esta', end="\n")#python中的print函数是自带\n(换行)print('esta', end="")#修改end变量的默认值,输出就不会自动换行啦

3.输入

3.1input()函数

number = input("请输入一个数字")#将输入的值赋给number变量print(type(number))#但是请注意!!!input接收的任何数据默认都是字符串数据类型

3.2转换数据类型

print(type(int(number)))#转化为int类型print(type(float(number)))#转化为float类型print(type(eval(number)))#eval()函数可以返回表达式中变量原本的值

4.运算符

4.1与C语言不同的基本运算符

t1 = 1/2#python中的/是真正去计算除法print(t1)t2 = 1//2#地板除,与C语言中除法一致print(t2)s = 2**3#表示2的3次方print(s)

4.2赋值运算符

#赋值运算符特殊的用法num1, float1, str1 = 10, 0.5, 'hello world'print(num1)print(float1)print(str1)a = b = 10print(a)print(b)

4.3复合赋值运算符

a = 100a += 1a -= 1b = 2b *= 3b /= 2

4.4比较运算符

a = 7b = 5print(a == b) # Falseprint(a != b) # Trueprint(a < b) # Falseprint(a > b) # Trueprint(a <= b) # Falseprint(a >= b) # True

4.5逻辑运算符

a = 1b = 2c = 3print((a < b) and (b < c)) # Trueprint((a > b) and (b < c)) # Falseprint((a > b) or (b < c)) # Trueprint(not (a > b))# True

5.if语句

5.1语法

if 条件:条件成立执行的代码1条件成立执行的代码2

5.2加上else

num = 12if num > 13:print("1")else:print("2")

5.3多重判断

num = 12if num > 13:print("1")elif num < 15:print("2")else:print("3")

5.4if的嵌套

t1 = 1t2 = 0if t1 == 1:print("t1=1")if t2 == 0:print("t2=0")

5.5三目运算符

a = 1b = 2c = a if a > b else b#条件成立返回a,条件不成立返回bprint(c)

6循环

6.1while循环

count = 0while count < 5:print(count)count += 1

6.2用while循环实现1到100的累加

i = 1result = 0while i <= 100:result += ii += 1print(result)

6.3break

i = 1while i <= 5:if i == 4:print(f'吃饱了')breakprint('吃了第%d个苹果' %i)i += 1

6.4continue

i = 1while i <= 5:if i == 3:print('有虫子,第%d个不吃' %i)# 在continue之前一定要修改计数器,否则会陷入死循环i += 1continueprint('吃了第%d个苹果' %i)i += 1

6.5循环的嵌套

i = 0j =0while i < 2:print('条件1成立执行的代码')i += 1while j < 2:print('条件2成立执行的代码')j += 1

6.6while else语句

i = 1while i <= 5:print('打你一下')i += 1else:print('打够了,不打了')

6.7for循环

for i in range(5):print(i)for i in "esta":print(i)

7.字符串

7.1定义字符串

#字符串是 Python 中最常用的数据类型。我们一般使用引号来创建字符串。a = 'hello world'b = "abcdefg"print(type(a))print(type(b))#'''...'''可以保留原文档的格式temp = ''' a is Tom b is Jack '''print(temp)

7.2索引

name = "abcdef"print(name[1])print(name[0])#与C语言一样,python中的索引也都是从0开始print(name[2])

7.3切片

#切片是指对操作的对象截取其中一部分的操作。**字符串、列表、元组**都支持切片操作。#序列[开始位置下标:结束位置下标:步长]name = "abcdefg"print(name[2:5:1]) # cdeprint(name[2:5]) # cdeprint(name[:5]) # abcdeprint(name[1:]) # bcdefgprint(name[:]) # abcdefgprint(name[::2]) # acegprint(name[:-1]) # abcdef, 负1表示倒数第一个数据print(name[-4:-1]) # defprint(name[::-1]) # gfedcba

7.4字符串一些常用的操作方法

# 字符串序列.find(子串, 开始位置下标, 结束位置下标)# find():检测某个子串是否包含在这个字符串中,# 如果在返回这个子串开始的位置下标,否则则返回-1。mystr = "hello world and hello esta and hello Python"print(mystr.find('and')) # 12print(mystr.find('and', 15, 32))# 27print(mystr.find('ands')) # -1# index():检测某个子串是否包含在这个字符串中,# 如果在返回这个子串开始的位置下标,否则则报异常。mystr = "hello world and hello esta and hello Python"print(mystr.index('and')) # 12print(mystr.index('and', 15, 32)) # 27print(mystr.index('ands')) # 报错

8列表

8.1定义列表

#列表可以一次性存储多个数据,且可以为不同数据类型。name_list = ['Tom', 'Lily', 'Rose']print(name_list[0]) # Tomprint(name_list[1]) # Lilyprint(name_list[2]) # Rose

8.2列表常用的一些操作

print(name_list.index('Lily', 0, 2)) #列表中index()同字符串# count():统计指定数据在当前列表中出现的次数。print(name_list.count('Lily')) # 1# len():访问列表长度,即列表中数据的个数。print(len(name_list)) # 3#in:判断指定数据在某个列表序列,如果在返回True,否则返回Falseprint('Lily' in name_list)# 结果:Trueprint('Lilys' in name_list)# 结果:False# not in:判断指定数据不在某个列表序列,如果不在返回True,否则返回Falseprint('Lily' not in name_list)# 结果:Falseprint('Lilys' not in name_list)# 结果:True# append():列表结尾追加数据。name_list = ['Tom', 'Lily', 'Rose']name_list.append('xiaoming')print(name_list)# 结果:['Tom', 'Lily', 'Rose', 'xiaoming']#如果append()追加的数据是一个序列,则追加整个序列到列表name_list = ['Tom', 'Lily', 'Rose']name_list.append(['xiaoming', 'xiaohong'])print(name_list)# 结果:['Tom', 'Lily', 'Rose', ['xiaoming', 'xiaohong']]# extend():列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表。name_list = ['Tom', 'Lily', 'Rose']name_list.extend('xiaoming')print(name_list)# 结果:['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']name_list = ['Tom', 'Lily', 'Rose']name_list.extend(['xiaoming', 'xiaohong'])print(name_list)# 结果:['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']# insert():指定位置新增数据。name_list = ['Tom', 'Lily', 'Rose']name_list.insert(1, 'xiaoming')print(name_list)# 结果:['Tom', 'xiaoming', 'Lily', 'Rose']#删除整个列表name_list = ['Tom', 'Lily', 'Rose']del name_listprint(name_list)#会报错#删除一个元素name_list = ['Tom', 'Lily', 'Rose']del name_list[0]print(name_list)#结果:['Lily', 'Rose']# pop():删除指定下标的数据(默认为最后一个),并返回该数据。name_list = ['Tom', 'Lily', 'Rose']del_name = name_list.pop(1)print(del_name)# 结果:Lilyprint(name_list)# 结果:['Tom', 'Rose']# remove():移除列表中某个数据的第一个匹配项。name_list = ['Tom', 'Lily', 'Rose']name_list.remove('Rose')print(name_list)# 结果:['Tom', 'Lily']# clear():清空列表name_list = ['Tom', 'Lily', 'Rose']name_list.clear()print(name_list) # 结果: []# 修改指定下标数据name_list = ['Tom', 'Lily', 'Rose']name_list[0] = 'aaa'print(name_list)# 结果:['aaa', 'Lily', 'Rose']# 排序:sort()num_list = [1, 5, 2, 3, 6, 8]num_list.sort()print(num_list)# 结果:[1, 2, 3, 5, 6, 8]# 复制name_list = ['Tom', 'Lily', 'Rose']name_li2 = name_list.copy()print(name_li2)# 结果:['Tom', 'Lily', 'Rose']# 列表的循环遍历(以下两种方法遍历的输出是一样的)name_list = ['Tom', 'Lily', 'Rose']#方法一i = 0while i < len(name_list):print(name_list[i])i += 1name_list = ['Tom', 'Lily', 'Rose']#方法二for i in name_list:print(i) #列表嵌套name_list = [['小明', '小红', '小绿'], ['Tom', 'Lily', 'Rose'], ['张三', '李四', '王五']]name_list[2][1]

9.元组

9.1定义元组

t1 = (10, 20, 30)# 如果定义的元组只有一个数据,那么这个数据后面也好添加逗号,# 否则数据类型为唯一的这个数据的数据类型t2 = (10,)print(type(t2)) # tuplet3 = (20)print(type(t3)) # int

9.2元组常见的操作

tuple1 = ('aa', 'bb', 'cc', 'bb')print(tuple1[0]) # aaprint(tuple1.index('aa')) # 0# count():统计某个数据在当前元组出现的次数。tuple1 = ('aa', 'bb', 'cc', 'bb')print(tuple1.count('bb')) # 2# len():统计元组中数据的个数。print(len(tuple1)) # 4#尝试修改元组内的值tuple1 = ('aa', 'bb', 'cc', 'bb')tuple1[0] = 'aaa'#会报错,不可以修改元组内的值# 但是如果元组里面有列表,修改列表里面的数据则是支持的tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)print(tuple2[2]) # 访问到列表tuple2[2][0] = 'aaaaa'print(tuple2)

10.字典

10.1定义字典

dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}dict2 = {}

10.2字典常用的操作

dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}dict1['name'] = 'Rose'#修改name对应的值print(dict1)# 结果:{'name': 'Rose', 'age': 20, 'gender': '男'}dict1['id'] = 110print(dict1)# 如果key存在则修改这个key对应的值;如果key不存在则新增此键值对# 结果:{'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}#删除字典中的键值对dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}del dict1['gender']print(dict1)# 结果:{'name': 'Tom', 'age': 20}#清空字典dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}dict1.clear()print(dict1) #结果: {}#通过键访问值dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}print(dict1['name']) # Tomprint(dict1['id']) # 报错#get方法: 如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None。dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}print(dict1.get('name')) # Tomprint(dict1.get('id', 110)) # 110print(dict1.get('id')) # None#返回所有键dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}print(dict1.keys()) #结果: dict_keys(['name', 'age', 'gender'])#返回所有值dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}print(dict1.values()) #结果: dict_values(['Tom', 20, '男'])#返回所有键值对dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}print(dict1.items()) #结果: dict_items([('name', 'Tom'), ('age', 20), ('gender', '男')])

11.集合

13.1定义集合

# 创建集合使用{}或set(), 但是如果要创建空集合只能使用set(),因为{}用来创建空字典。#集合有去重功能s1 = {10, 20, 30, 40, 50}print(s1)s4 = set()print(type(s4)) # sets5 = {}print(type(s5)) # dict

13.2集合常用的操作

#添加s1 = {10, 20}s1.add(100)s1.add(10)print(s1) # {100, 10, 20}#添加序列s1 = {10, 20}# s1.update(100) # 报错s1.update([100, 200])s1.update('abc')print(s1)#删除元素s1 = {10, 20}s1.remove(10)print(s1)

14.一些公用的操作

14.1合并

#+合并# 1. 字符串 str1 = 'aa'str2 = 'bb'str3 = str1 + str2print(str3) # aabb# 2. 列表 list1 = [1, 2]list2 = [10, 20]list3 = list1 + list2print(list3) # [1, 2, 10, 20]# 3. 元组 t1 = (1, 2)t2 = (10, 20)t3 = t1 + t2print(t3) # (10, 20, 100, 200)

14.2复制

# *复制# 1. 字符串print('-' * 10) # ----------# 2. 列表list1 = ['hello']print(list1 * 4) # ['hello', 'hello', 'hello', 'hello']# 3. 元组t1 = ('world',)print(t1 * 4) # ('world', 'world', 'world', 'world')

14.3求最大最小值

# 1. 字符串str1 = 'abcdefg'print(max(str1)) # g# 2. 列表list1 = [10, 20, 30, 40]print(max(list1)) # 40# 1. 字符串str1 = 'abcdefg'print(min(str1)) # a# 2. 列表list1 = [10, 20, 30, 40]print(min(list1)) # 10

14.4容器类型的转换

list1 = [10, 20, 30, 40, 50, 20]s1 = {100, 200, 300, 400, 500}print(tuple(list1))#转换为元组print(tuple(s1))t1 = ('a', 'b', 'c', 'd', 'e')s1 = {100, 200, 300, 400, 500}print(list(t1))#转化为列表print(list(s1))list1 = [10, 20, 30, 40, 50, 20]t1 = ('a', 'b', 'c', 'd', 'e')print(set(list1))#转换为集合print(set(t1))

15.函数初识

#定义函数def print_fuction():print("esta")#调用函数 print_fuction()

16.库的调用

#导入一个模块import somemodule(模块)somemodule.somefunction() #调用该模块的某个函数#从模块中导入(一些)函数from somemodule import somefunction[,anotherfunction,...]somefunction() #给模块指定别名import somemodule as mm.somefunction()#导入模块中的一切函数from somemodule import *somefunction()#导入一个函数并指定别名from somemodule import somefuntion as ff()

一般,我们用前三种表达方式更多一些

17.time库

要使用time库,我们首先应该将time库导入到我们的程序中

import time

关于time库,我们首先给出常用方法

#1.0获得当前时间戳,是从1970年某一个时刻到今天的秒数print(time.time())#1.1易于阅读的时间:(被保存为字符串形式)print(time.ctime())#1.2易于计算机阅读的时间(保存为struct结构)print(time.gmtime())# 此外,python还提供了时间的标准化输出。t = time.gmtime()strtime = time.strftime("%Y-%m-%d %H:%M:%S",t)# time库通过time.perf_counter来获得当前时间戳,保存为浮点型start = time.perf_counter()# 用这个函数,我们可以计算程序执行的过程中的时间time.sleep(2)end = time.perf_counter()print(end - start)

18.jieba库

jieba库是python中非常强的中文分词库。但jieba并不是python自带的库,我们要通过下载才能使用。

首先按下win+R,在对话框中输入cmd。

然后将这一段拷贝到命令行中,回车安装(确保联网)

pip install -i https://pypi.tuna./simple jieba

以下给出jieba库的用法:

支持三种分词模式:

精确模式,试图将句子最精确地切开,适合文本分析;全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。

#jieba库的使用import jiebas = '沙宏伟学长喜欢python't = "辰辰学长对虾过敏并且喜欢喝奶茶"print(jieba.lcut(s)) #精确模式:返回一个列表的分词结果print(jieba.lcut(t,cut_all=True)) #全模式:返回所有有关联的分词结果print(jieba.lcut_for_search(s)) #搜索模式:更为智能的分词结果jieba.add_word('沙宏伟') #向搜索模式中添加新词print(jieba.lcut(s)) #精确模式:返回一个列表的分词结果

19.numpy库

1.ndarray数组基础

python中用列表保存一组值,可将列表当数组使用。另外,python中有array模块,但它不支持多维数组,无论是时列表还是array模块都没有科学运算函数,不适合做矩阵等科学计算。numpy没有使用python本身的数组机制,而是提供了ndarray对象,该对象不仅能方便地存取数组,而且拥有丰富的数组计算函数。

使用前先导入Numpy模块

import numpy as np#或from numpy import *

1)数组的创建及使用

x = np.array([[1.0,0.0,0.0],[0.,1.,2.]]) #定义了一个二维数组,大小为(2,3)xarray([[1., 0., 0.],[0., 1., 2.]])x.ndim #数组维度数2x.shape #数组的维数,返回的格式(n,m),其中n为行数,m为列数(2, 3)x.size #数组元素的总数6x.dtype #数组元素类型dtype('float64') #64位浮点型x.itemsize #每个元素占有的字节大小8

还有两种创建序列数组的函数arrange和linspace,和range函数类似,但它们都属于Numpy里面。

arange(a,b,c) 参数分别表示开始值,结束值,步长

linspace(a,b,c) 参数分别表示开始值,结束值,元素数量

还可以调用它们自身的方法reshape()指定形状

arange(15).reshape(3,5)array([[ 0, 1, 2, 3, 4],[ 5, 6, 7, 8, 9],[10, 11, 12, 13, 14]])arange(10,30,5)array([10, 15, 20, 25])arange(0,2,0.3)array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])linspace(0,2,9) # 0~2之间生成9个数字array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])

还有两种创建概率分布的形式创建ndarray数组

高斯分布(正态分布)

np.random.randn(shape):生成对应形状(shape)的高斯分布

np.random.normal(loc, scale, size):生成均值为loc,标准差为scale,形状(shape)为size的高斯分布

均匀分布

np.random.rand(shape):生成对应形状(shape)的均匀分布

np.random.uniform(low, high, size):生成一个从[low, high)中随即采样的,样本数量为size的均匀分布

a = np.random.randn(10) # 长度为10的一个一维数组aarray([ 0.12939473, 0.43128511, 1.20540157, 0.54083603, 0.80768359,-1.24217976, -0.9713093 , 1.43538807, -1.07227227, -1.27176462])b = np.random.normal(0, 1, (2,4)) # 均值为1,方差为0,形状为(2,4)的二维数组barray([[ 0.4132305 , -2.06728849, 1.15189397, -1.1115],[ 0.39955198, -0.89664908, -0.61361683, -0.13166113]])c = np.random.rand(2,3) # 生成一个形状为(2,3)的均匀分布二维数组carray([[0.57091351, 0.39960244, 0.77019683],[0.11316102, 0.59354993, 0.37849038]])d = np.random.uniform(-1,1,10)darray([-0.34374858, -0.27026865, 0.27073922, -0.42654097, -0.38736897,0.16293278, -0.79578655, -0.04825995, 0.28444576, 0.99118406])

2)特殊数组

zeros数组:全零数组,元素全为零。

ones数组:全1数组,元素全为1。

empty数组:空数组,元素全近似为0。

zeros((3,4))array([[0., 0., 0., 0.],[0., 0., 0., 0.],[0., 0., 0., 0.]])ones((2,3,4),dtype = int16)array([[[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1]],[[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1]]], dtype = int16)empty((5,3))array([[6.23042070e-307, 1.42417221e-306, 1.37961641e-306],[1.11261027e-306, 1.11261502e-306, 1.42410839e-306],[7.56597770e-307, 6.23059726e-307, 1.42419530e-306],[7.56599128e-307, 1.11260144e-306, 6.89812281e-307],[2.22522596e-306, 2.22522596e-306, 2.56761491e-312]])

3)数组索引

Numpy数组每个元素,每行元素,每列元素都可以用索引访问。

c = np.arange(24).reshape(2,3,4) # reshape()改变数组形状print(c)[[[ 0 1 2 3][ 4 5 6 7][ 8 9 10 11]][[12 13 14 15][16 17 18 19][20 21 22 23]]]print(c[1,2,:])[20 21 22 23]print(c[0,1,2])6

4)数组运算

算术运算:数组的加减乘除以及乘方运算方式为,相应位置的元素分别进行运算。

a = array([20,30,40,50])aa = arange(1,5)a / aaarray([20. , 15. , 13.33333333, 12.5 ])b = arange(4)barray([0, 1, 2, 3])c = a - bcarray([20, 29, 38, 47])A.sum()A.min()A.max()

逻辑运算

arr > a : 返回arr中大于a的一个布尔值数组

arr[arr>a] : 返回arr中大于a的数据构成的一维数组

np.all(): 括号内全为真则返回真,有一个为假则返回false

np.any() : 括号内全为假则返回假,有一个为真则返回真

np.where(): 三元预算符, 判断同时赋值

如:np.where(arr>0, 1, 0)

复合逻辑运算:

与:np.logical_and(): 括号为一系列表达式

或:np.logical_or()

统计运算

统计指标函数:min, max, mean, median, var, std

np.函数名

ndarray.方法名

axis参数:axis=0代表列,axis=1代表行

最大值最小值的索引函数:

np.argmax(arr, axis=)

np.argmin(arr, axis=)

5)数组的拷贝

数组的拷贝分浅拷贝和深拷贝两种,浅拷贝通过数组变量的赋值完成,深拷贝使用数组对象的copy方法。

浅拷贝只拷贝数组的引用,如果对拷贝进行修改,源数组也将修改。如下:

a = ones((2,3))aarray([[1., 1., 1.],[1., 1., 1.]])b = ab[1,2] = 2aarray([[1., 1., 1.],[1., 1., 2.]])barray([[1., 1., 1.],[1., 1., 2.]])

深拷贝会复制一份和源数组一样的数组,新数组与源数组会存放在不同内存位置,因此对新数组的修改不会影响源数组。如下:

a = ones((2,3))b = a.copy()b[1,2] = 2aarray([[1., 1., 1.],[1., 1., 1.]])barray([[1., 1., 1.],[1., 1., 2.]])

6)numpy降维

ravel():返回一维数组,但是改变返回的一维数组内容后,原数组的值也会相应改变

flatten():返回一维数组,改变返回的数组不影响原数组

aarray([[1, 2, 3],[7, 8, 9]])barray([[4, 5, 6],[1, 2, 3]])c = a.ravel()carray([1, 2, 3, 7, 8, 9])d = b.flatten()darray([4, 5, 6, 1, 2, 3])c[0]=100carray([100, 2, 3, 7, 8, 9])aarray([[100, 2, 3],[ 7, 8, 9]])d[0] = 100darray([[100, 100],[ 6, 1],[ 2, 3]])barray([[4, 5, 6],[1, 2, 3]])

2.矩阵

1)创建矩阵

Numpy的矩阵对象与数组对象相似,主要不同之处在于,矩阵对象的计算遵循矩阵数学运算规律。矩阵使用matrix函数创建。

from numpy import matrixA = matrix('1.0 2.0;3.0 4.0')Amatrix([[1., 2.],[3., 4.]])b = matrix([[1.0,2.0],[3.0,4.0]])bmatrix([[1., 2.],[3., 4.]])

2)矩阵运算

矩阵的常用数学运算有转置,乘法,求逆等。

A.T#转置matrix([[1., 3.],[2., 4.]])x = matrix('5.0 7.0')y = x.Tymatrix([[5.],[7.]])print(A*y) #矩阵乘法[[19.][43.]]print(A.I) #逆矩阵[[-2. 1. ][ 1.5 -0.5]]

3.Numpy线性代数相关函数

numpy.dot()

此函数返回两个数组的点积。 对于二维向量,其等效于矩阵乘法。 对于一维数组,它是向量的内积。 对于 N 维数组,它是a的最后一个轴上的和与b的倒数第二个轴的乘积。

a = np.array([[1,2],[3,4]])b = np.array([[11,12],[13,14]])np.dot(a,b)array([[37, 40],#[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]][85, 92]])numpy.vdot()此函数返回两个向量的点积。 如果第一个参数是复数,那么它的共轭复数会用于计算。 如果参数id是多维数组,它会被展开。np.vdot(a,b)130 #1*11+2*12+3*13+4*14=130numpy.inner()此函数返回一维数组的向量内积。 对于更高的维度,它返回最后一个轴上的和的乘积。x = np.array([1,2,3])y = np.array([0,1,0])print(np.inner(x,y))2# 等价于 1*0+2*1+3*0numpy.matmul()函数返回两个数组的矩阵乘积。 虽然它返回二维数组的正常乘积,但如果任一参数的维数大于2,则将其视为存在于最后两个索引的矩阵的栈,并进行相应广播。另一方面,如果任一参数是一维数组,则通过在其维度上附加 1 来将其提升为矩阵,并在乘法之后被去除。#对二维数组(列表),就相当于矩阵乘法a = [[1,0],[0,1]]b = [[4,1],[2,2]]print(np.matmul(a,b))[[4 1][2 2]]#二维和一维运算a = [[1,0],[0,1]]b = [1,2]print(np.matmul(a,b))[1 2]print(np.matmul(b,a))[1 2]#维度大于2的a = np.arange(8).reshape(2,2,2)b = np.arange(4).reshape(2,2)print(np.matmul(a,b))[[[ 2 3][ 6 11]][[10 19][14 27]]]

numpy.linalg.det()

行列式在线性代数中是非常有用的值。 它从方阵的对角元素计算。 对于 2×2 矩阵,它是左上和右下元素的乘积与其他两个的乘积的差。

换句话说,对于矩阵[[a,b],[c,d]],行列式计算为ad-bc。 较大的方阵被认为是 2×2 矩阵的组合。

numpy.linalg.det()函数计算输入矩阵的行列式。

a = np.array([[1,2],[3,4]])print(np.linalg.det(a))-2.0000000000000004b = np.array([[6,1,1],[4,-2,5],[2,8,7]])print(b)[[ 6 1 1][ 4 -2 5][ 2 8 7]]print(np.linalg.det(b))-306.0print(6 * (-2 * 7 - 5 * 8) - 1 * (4 * 7 - 5 * 2) + (4 * 8 - 2 * 2))-306

numpy.linalg.solve()

该函数给出了矩阵形式的线性方程的解。

例:

x + y + z = 6

2y + 5z = -4

2x + 5y - z = 27

写成矩阵形式

可表示为AX=B

即求X=A^(-1)B

逆矩阵可以用numpy.linalg.inv()函数来求

x = np.array([[1,2],[3,4]])y = np.linalg.inv(x)xarray([[1, 2],[3, 4]])yarray([[-2. , 1. ],[ 1.5, -0.5]])np.dot(x,y)array([[1.0000000e+00, 0.0000000e+00],[8.8817842e-16, 1.0000000e+00]])a = np.array([[1,1,1],[0,2,5],[2,5,-1]])print('数组a:')print(a)ainv = np.linalg.inv(a)print('a的逆矩阵')print(ainv)print('矩阵b:')b = np.array([[6],[-4],[27]])print(b)print('计算:A^(-1)B:')x = np.linalg.solve(a,b)print(x)

20.NumPy Matplotlib

Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用,如 PyQt 。

实例

import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y) plt.show()

np.arange() 函数创建 x 轴上的值。y 轴上的对应值存储在另一个数组对象 y 中。 这些值使用 matplotlib 软件包的 pyplot 子模块的 plot() 函数绘制。

图形由 show() 函数显示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zcjwlOsm-1606637152135)(C:\Users\10989\Desktop\培训\1.jpg)]

实例

以下是颜色的缩写:

要显示圆来代表点,而不是上面示例中的线,请使用 ob 作为 plot() 函数中的格式字符串。

实例

import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y,"or") plt.show()

绘制正弦波

以下实例使用 matplotlib 生成正弦波图。

实例

import numpy as np import matplotlib.pyplot as plt # 计算正弦曲线上点的 x 和 y 坐标 x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("sine wave form") # 使用 matplotlib 来绘制点 plt.plot(x, y) plt.show()

subplot()

subplot() 函数允许你在同一图中绘制不同的东西。

以下实例绘制正弦和余弦值:

实例

import numpy as np import matplotlib.pyplot as plt # 计算正弦和余弦曲线上的点的 x 和 y 坐标 x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # 建立 subplot 网格,高为 2,宽为 1 # 激活第一个 subplot plt.subplot(2, 1, 1) # 绘制第一个图像 plt.plot(x, y_sin) plt.title('Sine') # 将第二个 subplot 激活,并绘制第二个图像 plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # 展示图像 plt.show()

bar()

pyplot 子模块提供 bar() 函数来生成条形图。

以下实例生成两组 x 和 y 数组的条形图。

实例

from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = 'center') plt.bar(x2, y2, color = 'g', align = 'center') plt.title('Bar graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show()

plt()

Matplotlib 可以将直方图的数字表示转换为图形。 pyplot 子模块的 plt() 函数将包含数据和 bin 数组的数组作为参数,并转换为直方图。

from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) plt.hist(a, bins = [0,20,40,60,80,100]) plt.title("histogram") plt.show()

同时绘制多条曲线

import matplotlib.pyplot as pltimport numpy as np# 从[-1,1]中等距去50个数作为x的取值x = np.linspace(-1, 1, 50)y1 = 2 * x + 1y2 = 2 ** x + 1# num表示的是编号,figsize表示的是图表的长宽plt.figure(num = 3, figsize = (8, 5)) plt.plot(x, y2)# 设置线条的样式plt.plot(x, y1, color = 'red', # 线条的颜色linewidth = 1.0, # 线条的粗细linestyle = '--' # 线条的样式)# 设置取值参数范围plt.xlim((-1, 2)) # x参数范围plt.ylim((1, 3)) # y参数范围# 设置点的位置new_ticks = np.linspace(-1, 2, 5)plt.xticks(new_ticks)# 为点的位置设置对应的文字。# 第一个参数是点的位置,第二个参数是点的文字提示。plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])# gca = 'get current axis'ax = plt.gca()# 将右边和上边的边框(脊)的颜色去掉ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')# 绑定x轴和y轴ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')# 定义x轴和y轴的位置ax.spines['bottom'].set_position(('data', 0))ax.spines['left'].set_position(('data', 0))plt.show()

多条曲线之曲线说明

import matplotlib.pyplot as pltimport numpy as np# 从[-1,1]中等距去50个数作为x的取值x = np.linspace(-1, 1, 50)y1 = 2 * x + 1y2 = 2 ** x + 1# 第一个参数表示的是编号,第二个表示的是图表的长宽plt.figure(num = 3, figsize = (8, 5)) plt.plot(x, y2)plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle = '--')# 设置取值参数plt.xlim((-1, 2))plt.ylim((1, 3))# 设置lableplt.xlabel("I am x")plt.ylabel("I am y")# 设置点的位置new_ticks = np.linspace(-1, 2, 5)plt.xticks(new_ticks)plt.yticks([-2, -1.8, -1, 1.22,3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])l1, = plt.plot(x, y2, label = 'aaa')l2, = plt.plot(x, y1, color = 'red', # 线条颜色linewidth = 1.0, # 线条宽度linestyle = '-.', # 线条样式label = 'bbb' #标签)# 使用legend绘制多条曲线plt.legend(handles = [l1, l2], labels = ['aaa', 'bbb'], loc = 'best')plt.show()

多个figure,并加上特殊点注释

import matplotlib.pyplot as pltimport numpy as np# 从[-1,1]中等距去50个数作为x的取值x = np.linspace(-1, 1, 50)y1 = 2 * x + 1y2 = 2 ** x + 1plt.figure(figsize = (12, 8)) # 第一个参数表示的是编号,第二个表示的是图表的长宽plt.plot(x, y2)plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle = '--')# gca = 'get current axis'ax = plt.gca()# 将右边和上边的边框(脊)的颜色去掉ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')# 绑定x轴和y轴ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')# 定义x轴和y轴的位置ax.spines['bottom'].set_position(('data', 0))ax.spines['left'].set_position(('data', 0))# 显示交叉点x0 = 1y0 = 2 * x0 + 1# s表示点的大小,默认rcParams['lines.markersize']**2plt.scatter(x0, y0, s = 66, color = 'b')# 定义线的范围,X的范围是定值,y的范围是从y0到0的位置# lw的意思是linewidth,线宽plt.plot([x0, x0], [y0, 0], 'k-.', lw = 2.5)# 设置关键位置的提示信息plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data',xytext=(+30, -30),textcoords='offset points',fontsize=16, # 这里设置的是字体的大小# 这里设置的是箭头和箭头的弧度arrowprops = dict(arrowstyle = '->',connectionstyle = 'arc3,rad=.2'))# 在figure中显示文字信息# 可以使用\来输出特殊的字符\mu\ \sigma\ \alphaplt.text(0, 3, r'$This\ is\ a\ good\ idea.\ \mu\ \sigma_i\ \alpha_t$',fontdict={'size':16,'color':'r'})plt.show()

tick能见度设置

import matplotlib.pyplot as pltimport numpy as np# 从[-1,1]中等距去50个数作为x的取值x = np.linspace(-1, 1, 50)y = 2 * x - 1plt.figure(figsize = (12, 8)) # 第一个参数表示的是编号,第二个表示的是图表的长宽# alpha是设置透明度的plt.plot(x, y, color='r', linewidth = 10.0, alpha = 0.5)# gca = 'get current axis'ax = plt.gca()# 将右边和上边的边框(脊)的颜色去掉ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')# 绑定x轴和y轴ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')# 定义x轴和y轴的位置ax.spines['bottom'].set_position(('data', 0))ax.spines['left'].set_position(('data', 0))# 可以使用tick设置透明度for label in ax.get_xticklabels() + ax.get_yticklabels():label.set_fontsize(12)label.set_bbox(dict(facecolor = 'y', edgecolor = 'None', alpha = 0.7))plt.show()

散点图

import matplotlib.pyplot as pltimport numpy as npn = 1024# 从[0]X = np.random.normal(0, 1, n)Y = np.random.normal(0, 1, n)T = np.arctan2(X, Y)plt.scatter(np.arange(5), np.arange(5))plt.xticks(())plt.yticks(())plt.show()

条形图

import matplotlib.pyplot as pltimport numpy as npn = 12X = np.arange(n)Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)plt.figure(figsize=(12, 8))plt.bar(X, +Y1, facecolor = '#9999ff', edgecolor = 'white')plt.bar(X, -Y2, facecolor = '#ff9999', edgecolor = 'white')for x, y in zip(X,Y1):# ha: horizontal alignment水平方向# va: vertical alignment垂直方向plt.text(x, y + 0.05, '%.2f' % y, ha = 'center', va = 'bottom')for x, y in zip(X,-Y2):# ha: horizontal alignment水平方向# va: vertical alignment垂直方向plt.text(x, y - 0.05, '%.2f' % y, ha = 'center', va = 'top')# 定义范围和标签plt.xlim(-.5, n)plt.xticks(())plt.ylim(-1.25, 1.25)plt.yticks(())plt.show()

contour等高线图

import matplotlib.pyplot as pltimport numpy as npdef get_height(x, y):# the height functionreturn (1-x / 2 + x ** 5 + y ** 3) *np.exp(-x ** 2 - y ** 2)n = 256x = np.linspace(-3, 3, n)y = np.linspace(-3, 3, n)X, Y = np.meshgrid(x, y)plt.figure(figsize=(14, 8))# use plt.contourf to filling contours# X, Y and value for (X, Y) point# 横坐标、纵坐标、高度、 、透明度、cmap是颜色对应表# 等高线的填充颜色plt.contourf(X, Y, get_height(X, Y), 16, alpah = 0.7, cmap = plt.cm.hot) # use plt.contour to add contour lines# 这里是等高线的线C = plt.contour(X, Y, get_height(X, Y), 16, color = 'black', linewidth = .5)# adding labelplt.clabel(C, inline=True, fontsize=16)plt.xticks(())plt.yticks(())plt.show()

image图片显示

import matplotlib.pyplot as pltimport numpy as np# image dataa = np.array([0.313660827978, 0.365348418405, 0.42373314,0.365348418405, 0.439599930621, 0.525083754405,0.42373314, 0.525083754405, 0.651536351379]).reshape(3,3)"""for the value of "interpolation", check this:/examples/images_contours_and_fields/interpolation_methods.htmlfor the value of "origin"= ['upper', 'lower'], check this:/examples/pylab_examples/image_origin.html"""# 这是颜色的标注# 主要使用imshow来显示图片,这里暂时不适用图片来显示,采用色块的方式演示。plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')plt.colorbar(shrink=.90) # 这是颜色深度的标注,shrink表示压缩比例plt.xticks(())plt.yticks(())plt.show()

3D数据图

import matplotlib.pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(12, 8))ax = Axes3D(fig)# 生成X,YX = np.arange(-4, 4, 0.25)Y = np.arange(-4, 4, 0.25)X,Y = np.meshgrid(X, Y)R = np.sqrt(X**2 + Y**2)# height valueZ = np.sin(R)# 绘图# rstride(row)和cstride(column)表示的是行列的跨度ax.plot_surface(X, Y, Z, rstride=1, # 行的跨度cstride=1, # 列的跨度cmap=plt.get_cmap('rainbow') # 颜色映射样式设置)# offset 表示距离zdir的轴距离ax.contourf(X, Y, Z, zdir='z', offest=-2, cmap='rainbow')ax.set_zlim(-2, 2)plt.show()

图中图

import matplotlib.pyplot as pltimport numpy as npfig = plt.figure(figsize=(10, 6))x = [1, 2, 3, 4, 5, 6, 7]y = [1, 3, 4, 2, 5, 8, 6]# 大图left, bottom, width, weight = 0.1, 0.1, 0.8, 0.8ax1 = fig.add_axes([left, bottom, width, weight])ax1.plot(x, y, 'r')ax1.set_xlabel(r'$x$')ax1.set_ylabel(r'$y$')ax1.set_title(r'$××Interesting××$')# 左上小图left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25ax2 = fig.add_axes([left, bottom, width, weight])ax2.plot(y, x, 'b')ax2.set_xlabel(r'$x$')ax2.set_ylabel(r'$y$')ax2.set_title(r'$title\ inside\ 1$')# 右下小图plt.axes([0.6, 0.2, 0.25, 0.25])# 将y的数据逆序输出[::1]plt.plot(y[::-1],x, 'g')plt.xlabel('x')plt.ylabel('y')plt.title(r'$title\ inside\ 2$')plt.show()

主次坐标轴

import matplotlib.pyplot as pltimport numpy as np# 从[0, 10]以0.1为间隔,形成一个列表x = np.arange(0, 10, 0.1)y1 = 0.05 * x**2y2 = -1 * y1fig, ax1 = plt.subplots()# 镜像(上下左右颠倒)ax2 = ax1.twinx()ax1.plot(x, y1, 'g-')ax2.plot(x, y2, 'b--')# 为轴进行命名ax1.set_xlabel(r'$X\ data$', fontsize=16)ax1.set_ylabel(r'$Y1$', color='g', fontsize=16)ax2.set_ylabel(r'$Y2$', color='b', fontsize=16)plt.show()

Animation动画

import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import animationfig, ax = plt.subplots()# 从[0, 2*np.pi]以0.01为间隔,形成一个列表x = np.arange(0, 2*np.pi, 0.01)# 这里只需要列表的第一个元素,所以就用逗号“,”加空白的形式省略了列表后面的元素line, = ax.plot(x, np.sin(x))def animate(i):line.set_ydata(np.sin(x + i/100))return line, def init():line.set_ydata(np.sin(x))# 这里由于仅仅需要列表的第一个参数,所以后面的就直接用空白省略了return line, ani = animation.FuncAnimation(fig=fig, func=animate, # 动画函数frames=100, # 帧数init_func=init, # 初始化函数interval=20, # 20msblit=True)plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。