软件技术部python培训

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 = 233
print(temp)

2.2格式化输出

age = 20 
name = 'abcd'
weight = 66.66
student_id = 1962654155788
print("我今年%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 = 10
print(a)
print(b)

4.3复合赋值运算符

a = 100
a += 1
a -= 1

b = 2
b *= 3
b /= 2
运算符描述实例
+=加法赋值运算符c += a 等价于 c = c + a
-=减法赋值运算符c -= a 等价于 c = c- a
*=乘法赋值运算符c *= a 等价于 c = c * a
/=除法赋值运算符c /= a 等价于 c = c / a
//=整除赋值运算符c //= a 等价于 c = c // a
%=取余赋值运算符c %= a 等价于 c = c % a
**=幂赋值运算符c ** = a 等价于 c = c ** a

4.4比较运算符

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

4.5逻辑运算符

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

5.if语句

5.1语法

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

5.2加上else

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

5.3多重判断

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

5.4if的嵌套

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

5.5三目运算符

a = 1
b = 2

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

6循环

6.1while循环

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

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

i = 1
result = 0
while i <= 100:
    result += i
    i += 1

print(result)

6.3break

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

6.4continue

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

6.5循环的嵌套

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

6.6while else语句

i = 1
while i <= 5:
    print('打你一下')
    i += 1
else:
    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])  # cde
print(name[2:5])  # cde
print(name[:5])  # abcde
print(name[1:])  # bcdefg
print(name[:])  # abcdefg
print(name[::2])  # aceg
print(name[:-1])  # abcdef, 负1表示倒数第一个数据
print(name[-4:-1])  # def
print(name[::-1])  # gfedcba

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

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

print(mystr.find('and'))  # 12
print(mystr.find('and', 15, 32))# 27
print(mystr.find('ands'))  # -1

# index():检测某个子串是否包含在这个字符串中,
# 如果在返回这个子串开始的位置下标,否则则报异常。
mystr = "hello world and hello esta and hello Python"

print(mystr.index('and'))  # 12
print(mystr.index('and', 15, 32))  # 27
print(mystr.index('ands'))  # 报错

8列表

8.1定义列表

#列表可以一次性存储多个数据,且可以为不同数据类型。
name_list = ['Tom', 'Lily', 'Rose']

print(name_list[0])  # Tom
print(name_list[1])  # Lily
print(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,否则返回False
print('Lily' in name_list)# 结果:True
print('Lilys' in name_list)# 结果:False

# not in:判断指定数据不在某个列表序列,如果不在返回True,否则返回False
print('Lily' not in name_list)# 结果:False
print('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_list
print(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)
# 结果:Lily
print(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 = 0
while i < len(name_list):
    print(name_list[i])
    i += 1

name_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))  # tuple

t3 = (20)
print(type(t3))  # int

9.2元组常见的操作

tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1[0])  # aa
print(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'] = 110
print(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'])  # Tom
print(dict1['id'])  # 报错


#get方法: 如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None。
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.get('name'))  # Tom
print(dict1.get('id', 110))  # 110
print(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))  # set

s5 = {}
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 + str2
print(str3)  # aabb


# 2. 列表 
list1 = [1, 2]
list2 = [10, 20]
list3 = list1 + list2
print(list3)  # [1, 2, 10, 20]

# 3. 元组 
t1 = (1, 2)
t2 = (10, 20)
t3 = t1 + t2
print(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 m
m.somefunction()

#导入模块中的一切函数
from somemodule import *
somefunction()

#导入一个函数并指定别名
from somemodule import somefuntion as f
f()

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

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.tsinghua.edu.cn/simple jieba

以下给出jieba库的用法:

支持三种分词模式:

  • 精确模式,试图将句子最精确地切开,适合文本分析;
  • 全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;
  • 搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。
#jieba库的使用
import jieba
s = '沙宏伟学长喜欢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)
x
array([[1., 0., 0.],
       [0., 1., 2.]])
x.ndim   #数组维度数
2
x.shape    #数组的维数,返回的格式(n,m),其中n为行数,m为列数
(2, 3)
x.size    #数组元素的总数
6
x.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的一个一维数组
a
array([ 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)的二维数组
b
array([[ 0.4132305 , -2.06728849,  1.15189397, -1.11201615],
       [ 0.39955198, -0.89664908, -0.61361683, -0.13166113]])
c = np.random.rand(2,3) # 生成一个形状为(2,3)的均匀分布二维数组
c
array([[0.57091351, 0.39960244, 0.77019683],
       [0.11316102, 0.59354993, 0.37849038]])
d = np.random.uniform(-1,1,10)
d
array([-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 / aa
array([20.        , 15.        , 13.33333333, 12.5       ])
b = arange(4)
b
array([0, 1, 2, 3])
c = a - b
c
array([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))
a
array([[1., 1., 1.],
       [1., 1., 1.]])
b = a
b[1,2] = 2
a
array([[1., 1., 1.],
       [1., 1., 2.]])
b
array([[1., 1., 1.],
       [1., 1., 2.]])

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

a = ones((2,3))
b = a.copy()
b[1,2] = 2
a
array([[1., 1., 1.],
       [1., 1., 1.]])
b
array([[1., 1., 1.],
       [1., 1., 2.]])
6)numpy降维

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

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

2.矩阵

1)创建矩阵

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

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

2)矩阵运算

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

A.T      #转置
matrix([[1., 3.],
        [2., 4.]])
x = matrix('5.0 7.0')
y = x.T
y
matrix([[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=130
numpy.inner()
此函数返回一维数组的向量内积。 对于更高的维度,它返回最后一个轴上的和的乘积。
x = np.array([1,2,3])
y = np.array([0,1,0])
print(np.inner(x,y))
2      # 等价于 1*0+2*1+3*0
numpy.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.0000000000000004
b = 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.0
print(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)
x
array([[1, 2],
       [3, 4]])
y
array([[-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)]

实例

字符描述
'-'实线样式
'--'短横线样式
'-.'点划线样式
':'虚线样式
'.'点标记
','像素标记
'o'圆标记
'v'倒三角标记
'^'正三角标记
'<'左三角标记
'>'右三角标记
'1'下箭头标记
'2'上箭头标记
'3'左箭头标记
'4'右箭头标记
's'正方形标记
'p'五边形标记
'*'星形标记
'h'六边形标记 1
'H'六边形标记 2
'+'加号标记
'x'X 标记
'D'菱形标记
'd'窄菱形标记
'|'竖直线标记
'_'水平线标记

以下是颜色的缩写:

字符颜色
'b'蓝色
'g'绿色
'r'红色
'c'青色
'm'品红色
'y'黄色
'k'黑色
'w'白色

要显示圆来代表点,而不是上面示例中的线,请使用 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 plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = 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 plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = 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))

# 设置lable
plt.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 plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = 2 ** x + 1

plt.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 = 1
y0 = 2 * x0 + 1
# s表示点的大小,默认rcParams['lines.markersize']**2
plt.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\ \alpha
plt.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 plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y = 2 * x - 1

plt.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 plt
import numpy as np

n = 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 plt
import numpy as np

n = 12
X = 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 plt
import numpy as np

def get_height(x, y):
    # the height function
    return (1-x / 2 + x ** 5 + y ** 3)  *np.exp(-x ** 2 - y ** 2)

n = 256
x = 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 label
plt.clabel(C, inline=True, fontsize=16)

plt.xticks(())
plt.yticks(())
plt.show()

这里写图片描述

image图片显示
import matplotlib.pyplot as plt
import numpy as np

# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)

"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/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 plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig)

# 生成X,Y
X = 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 value
Z = 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 plt
import numpy as np

fig = 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.8
ax1 = 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.25
ax2 = 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 plt
import numpy as np

# 从[0, 10]以0.1为间隔,形成一个列表
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1


fig, 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 plt
import numpy as np
from matplotlib import animation

fig, 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,  # 20ms
                              blit=True)

plt.show()

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值