numpy的基础练习
- 给定一个二维矩阵,如何交换其中两行的元素?
①代码:
n1=np.random.randint(0,1000,size=(7,8))
n1
n1[[1,0,2,3,4,5,6]]
②运行:
- 创建一个100000000长度的随机数组,使用两种方法对其求三次方,并比较所用时间
①代码:
n2=np.random.random(size=100000000)
n2
n2=np.random.randint(0,100000000,(5))
n2
%timeit np.power(n2,3)
%timeit n2**3
n2_2=np.dot(n2,n2)
%timeit np.dot(n2_2,n2)
②运行:
- 创建一个长度为10的随机数组并将最大值替换为0
①代码:
nd=np.random.randint(0,10,size=10)
display(nd)
index_max=nd.argmax()
nd[index_max]
all_index_max=np.argwhere(nd==nd[index_max]).reshape(-1)
all_index_max
nd[all_index_max]=-100
nd
②运行:
- 创建一个每一行都是从0到10的11*11矩阵
①代码:
s=[0,1,2,3,4,5,6,7,8,9,10]
nd=np.array(s*11)
nd.reshape(11,11)
n4=np.arange(0,11,1)
n4
n4_1=np.arange(0,121).reshape(11,11)
n4_1
n4_1[0:11]=n4
n4_1
②运行:
- 创建一个10*10的ndarray对象,且矩阵边界全为1,里面全为0
①代码:
nd=np.zeros(shape=(10,10),dtype=np.int8)
nd[[0,9]]=1
nd[:,[0,9]]=1
nd
a1=np.ones((10,10))
a1
a1[1:-1,1:-1]=0
a1
②运行:
- 给定一个4维矩阵,如何得到最后两维的和?
①代码:
n5=np.random.randint(0,100,size=(2,3,3,3))
n5
n5.sum(axis=(2,3))
n5.sum(axis=(-1,-2))
②运行:
- 创建一个53随机矩阵和一个32随机矩阵,求矩阵积
①代码:
n6_1=np.random.randint(0,100,size=(5,3))
n6_1
n6_2=np.random.randint(0,100,(3,2))
n6_2
np.dot(n6_1,n6_2)
②运行:
- 打印出以下函数(要求使用np.zeros创建8*8的矩阵):
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
①代码:
nd=np.ones(shape=(8,8),dtype=int)
nd[::2,::2]=0
nd[1::2,1::2]=0
nd
n8=np.zeros(shape=(8,8))
n8
n8[1::2,::2]=1
n8[::2,1::2]=1
n8
②运行:
- 创建一个元素为从10到49的ndarray对象
①代码:
np.random.randint(10,50,size=10)
np.linspace(10,49,10)
a=np.arange(10,50)
a
②运行:
教材一二章基础例题练习
- 输出
代码:
print("Run the code in this cell")
结果:
- Markdown
代码:
# This one
## This two
### This there
结果:
- 语言综合实例
代码:
import random
def fib_loop(n):
listNum = []
a, b = 0, 1
for i in range(n):
a, b = b, a + b
listNum.append(a)
return listNum
listPlan = ['英雄联盟', 'lol', '穿越火线', 'cf', ' 反恐精英', 'csgo', '地下城与勇士', 'dnf']
listNum = fib_loop(6)
varIdx = random.randint(0, 5)
varRandom = listNum[varIdx]
print('今日计划:', listPlan[varRandom])
结果:
(程序首先定义了fib_loop函数,用来生成斐波那契数列,并在主程序中调用了fib_loop函数,生成的斐波那契数列为[1,1,2,3,5,8]。程序通过包含random模块,并使用random.randint(0,5)函数生成了0~5的随机整数。然后将此随机数作为下标读取对应位置的斐波那契数,再使用该斐波那契数作为listPlan 数组的下标,得到推荐事件。可以看出,每次推荐的事件均为“学习”。)
- 数值类型不可改变
代码:
i = 3
print(id(i))
i += 1
print(id(i))
结果:
(Python的数字类型包括int,float,bool和complex复数类型。当指定一个值时,就创建了一个Number类型的对象)
- 字符串的访问
代码:
str = 'Picture'
print(str[1:3])
print(str[-3:-1])
print(str[3:-1])
print(str[-6:7])
print(str[2:])
print(str * 2)
print(str + "TEST")
结果:
- 列表的访问
代码:
list = ['a', 56, 1.13, 'HelloWorld', [7, 8, 9]]
print(list)
print(list[4])
print(list[-2:5])
print(list[2:])
结果:
(正序访问的时候,索引值从0开始,截取从头下标到尾下标减1位置的元素;如果是逆序访问,则-1是末尾位置。)
- 列表的遍历
代码:
lis=['瞎子','李青','盲僧','小学僧','Lee Sin']
# 直接遍历
print(lis)
# 按索引遍历
for i in enumerate(lis):
print(i)
# 下标遍历
for i in range(len(lis)):
print(lis[i])
结果:
- 字典的访问
代码:
dict = {'Name': 'Mary', 'Age': 7, 'Class': 'First'}
print(dict)
print("Name: ", dict['Name'])
print("Age: ", dict['Age'])
部分:
- 集合成员检测
代码:
var = {'LiLei', 'HanHua', 'HanMeiMei', 'ZhangSan', 'Lisi'}
result='LiLei' in var
print(result)
result='LiLei' not in var
print(result)
部分:
- 使用readline()函数逐行读取文件
with open('data.txt') as f:
line1 = f.readline()
line2 = f.readline()
print(line1)
print(line2)
print(line1.strip())
print(line2.strip())
print(line1.split())
numpy、pandas、matplotlib三个库的例题练习
一,numpy库的例题
- 用np.where()函数实现数据筛选
import numpy as np
num=np.random.normal(0,1,(3,4))
print(num)
num[num<0.5]=0
print(num)
print(np.where(num>0.5,1,0))
结果:
- 使用嵌套for循环对nadarray数组进行迭代遍历
代码:
import numpy as np
a= np.arange(0,60,5)
a=a.reshape(3,4)
for xline in a:
for yitem in xline:
print(yitem,end='')
结果:
- 创建二维ndarray的切片
代码:
import numpy as np
arr=np.arange(24).reshape(4,6)
print('arr=\n',arr)
arr1=arr[1:,:3]
print('B =\n',arr1)
结果:
二,pandas库的例题
- 为一个地理位置数据创建Series对象
代码:
import pandas as pd
#使用列表创建,索引值为默认值
print('--------列表创建Series---------')
s1 = pd.Series([1,1,1,1,1])
print(s1)
print('--------字典创建Series---------')
s2 = pd.Series({'Longitude':39,'Latitude':116,'Tamperature':23})
print('Frist value in s2:',s2['Longtitude'])
print('--------用序列作Series索引---------')
#使用range()函数生成的迭代序列设置索引值
s3 = pd.Series([3.4,0.8,2.1,0.3,1.5],range(5,10))
print('Frist value in s3:',s3[5])
结果:
- 对上面创建的s2,将温度增加2度,设置城市为北京
代码:
s2["city"]="beijing"
s2['Temperature']+=2
s2
结果:
- 为s2添加一项湿度数据
代码:
stiny = pd.Series({'humidity':84})
s4=s2.append(stiny)
print('------------原Series:-------------\n',s2)
print('------------新Series:-------------\n',s4)
结果:
- 创建DataFrame对象
代码:
import pandas as pd
dict1 = {'col1':[1,2,5,7],'col2':['a','b','c','d']}
df = pd.DataFrame(dict1)
df
结果:
三,matplotlib库的例题
- 绘制简单直线
代码:
import matplotlib.pyplot as plt
import numpy as np
a=np.arange(10)
plt.xlabel('x')
plt.ylabel('y')
plt.plot(a,a*1.5,a,a*2.5,a,a*3.5,a,a*4.5)
plt.legend(['1.5x','2.5x','3.5x','4.5x'])
plt.title('simple lines')
plt.show()
结果:
- 三角函数
代码:
# np.linespace()
x=np.linspace(-np.pi,np.pi,256,endpoint=True)
# 对 x 进行 cos 计算
C=np.cos(x)
# 对 x 进行 sin 计算
S=np.sin(x)
# 绘制折线图
plt.plot(x,C)
plt.plot(x,S)
plt.show()
结果:
- 在子画布上画图
代码:
import matplotlib.pyplot as plt
import numpy as np
#在子画布上画三个图表
flt = plt.figure()
ax1 = flt.add_subplot(2,2,1)
x = np.arange(-1,1,0.01)
plt.plot(x,np.sin(x))
ax2 = flt.add_subplot(2,2,2)
plt.plot(x,np.cos(x))
ax3 = flt.add_subplot(2,2,3)
plt.plot(x,np.tan(x))
结果:
- 绘制series数据
代码:
#绘制series数据
import matplotlib.pyplot as plt
import pandas as pd
plt.xlabel("x")
plt.ylabel("y")
pd.Series([1.1,3.2,4.5,9.5,4.2,3.5,6.4,7.4,6.5,1.0,2.3]).plot(kind="line",style="--")
plt.show()
结果:
- 饼状图
代码:
# 饼图
def youxi():
"""
youxi
"""
# 生成测试数据
sizes = [15, 30, 45, 10]
labels = ["cf", "lol", "dnf", "csgo"]
colors = ["yellowgreen", "gold", "red", "lightcoral"]
# 设置标题
plt.title("youxi")
# 设置突出参数
explode = [0, 0.05, 0, 0]
# 画饼状图
patches, l_text, p_text = plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct="%1.1f%%", shadow=True, startangle=90)
plt.axis("equal")
# 图形显示
plt.show()
return
if __name__ == "__main__":
# 运行
youxi()
结果:
什么是图灵测试
图灵测试(Turing test)是由艾伦·图灵(Alan Turing)于1950年提出的一种测试,用于评估一个机器是否能够表现出人类水平的智能。
测试过程中,一名人类评判者与一个机器人和一名真人进行交流,但评判者无法看到他们的身份。如果评判者无法确定哪一个是机器人,则机器人被认为通过了测试,即表现出了与真人相似的智能。
图灵测试成为了人工智能领域的一个标志性问题,也促进了人工智能技术的发展。虽然现今还没有一个机器完全通过了图灵测试,但是很多机器都已经能够实现一些人类的智能表现,如语音识别、自然语言处理、图像识别等领域。
总结
这次的作业让我对python这门完全陌生的语言有了最基本的了解,能用其完成简单的数据处理操作,其中对于numpy个人认为主要是处理一些数组类型的数据,而pandas则是更为全面的数据分析工具,能处理多种类型的数据,matplotlib则是主要用来画图,将数据转换为图形,让数据更为直观的表现出来
参考
https://blog.csdn.net/Dorisi_H_n_q/article/details/82259786