1-3章python练习

python数据处理
##引入库
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt

%matplotlib inline

基本数据类型
1.number数据类型
数值类型不可改变
i =3
print(id(i))
i +=1
print(id(i))

2690720885104
2690720885136
2.String类型
字符串的访问
str = ‘Picture’
print(str[1:3]) #第二第三个字符
print(str[-3:-1]) #倒数第二第三个字符

ic
ur
字符串赋值
word=‘Python’ #修改内容需要重新使用赋值语句
word=‘python’

列表的遍历
lis =[‘1’,‘2’,‘3’,‘4’,‘5’]
for item in lis: #直接遍历
print(item)
for i in enumerate(lis): #索引遍历
print(i)
for i in range(len(i)): #下标遍历
print(lis[i])

1
2
3
4
5
(0, ‘1’)
(1, ‘2’)
(2, ‘3’)
(3, ‘4’)
(4, ‘5’)
1
2
Dictionary字典
#字典的访问
dict ={‘name’:1,‘age’: 3,‘class’:5}
print(dict);
print(dict[‘age’])
#添加字典的值
dict[‘pp’]=20
print(dict)
#修改
dict.update({‘name’:300})
print(dict)
#删除
del dict[‘name’]
print(dict)
#清除字典
dict.clear()
print(dict)

{‘name’: 1, ‘age’: 3, ‘class’: 5}
3
{‘name’: 1, ‘age’: 3, ‘class’: 5, ‘pp’: 20}
{‘name’: 300, ‘age’: 3, ‘class’: 5, ‘pp’: 20}
{‘age’: 3, ‘class’: 5, ‘pp’: 20}
{}
数据文件读写
1.打开文件
例如:f= open(‘xxx.txt’,‘w’)
2.写入文件
f.write(‘some data’)
3.关闭文件
f.close()

读取文件

1.file.read([count])
2.file.readline()
3.file.readlines()

Python常用机器学习库
Numpy
ndarray
##创建ndarray
a = np.array([1,2,3]) ##创建一个一维数组
b = np.array([[1,2],[3,4]]) ##创建一个二维数组
c = np.array([1,2,3],dtype=np.complex) ##设置数组类型为复数

C:\Users\86152\AppData\Local\Temp\ipykernel_21348\3060588549.py:4: DeprecationWarning: np.complex is a deprecated alias for the builtin complex. To silence this warning, use complex by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use np.complex128 here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
c = np.array([1,2,3],dtype=np.complex) ##设置数组类型为复数
##使用astype()修改数据类型
y=np.array(5,dtype=“int”)
y=y.astype(“float32”)
print(y.dtype)

float32
Numpy数组属性##调整数组形状
arr = np.array([0,1,2,3,4,5,6,7])
print(arr.ndim)
arr3D = arr.reshape(2,2,2)
print(arr3D)
print(arr3D.ndim)

1
[[[0 1]
[2 3]]

[[4 5]
[6 7]]]
3
##显示数组得维度
print(arr3D.shape)

(2, 2, 2)
##调整数组大小
a = np.array([[1,2,3],[1,4,5]])
a.shape=(3,2)
print(a)

[[1 2]
[3 1]
[4 5]]
其他创建数组得方式
##创建一个空数组
x= np.empty([3,2])
print(x)

[[0. 0.]
[0. 0.]
[0. 0.]]
##创建一个全0数组
x=np.zeros(5)
print(x)

[0. 0. 0. 0. 0.]
##创建一个全1数组
x= np.ones(5)
print(x)
x=np.ones([2,2],dtype= int)
print(x)

[1. 1. 1. 1. 1.]
[[1 1]
[1 1]]
产生数列得函数
##range函数
arr =range(0,5,1)
print(arr)

range(0, 5)
##arange函数
arr1=np.arange(3,9,0.2)
arr1

array([3. , 3.2, 3.4, 3.6, 3.8, 4. , 4.2, 4.4, 4.6, 4.8, 5. , 5.2, 5.4,
5.6, 5.8, 6. , 6.2, 6.4, 6.6, 6.8, 7. , 7.2, 7.4, 7.6, 7.8, 8. ,
8.2, 8.4, 8.6, 8.8])
##linspace函数(等差数列)
arr2 =np.linspace(1,5,10)
arr2

array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])
随机函数创建数组
##创建随机数组
np.random.rand(2,3)

array([[0.80515724, 0.27742985, 0.00421546],
[0.91577485, 0.39002375, 0.0450897 ]])
np.random.randint(0,10,(2,2))

array([[4, 1],
[1, 0]])
np.random.uniform(1,2,(2,3))

array([[1.20650436, 1.05085402, 1.33838449],
[1.20658977, 1.39523264, 1.7678235 ]])
切片迭代和索引
##切片
arr = np.arange(24).reshape(4,6)
print(arr)
arr1=arr[1:,:3]
print(arr1)
arr2=arr1.copy()
print(arr2)

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
[[ 6 7 8]
[12 13 14]
[18 19 20]]
[[ 6 7 8]
[12 13 14]
[18 19 20]]
##迭代
a=np.arange(0,60,5).reshape(3,4)
for xline in a:
for yitem in xline:
print(yitem,end= ’ ')

0 5 10 15 20 25 30 35 40 45 50 55
numpy计算
条件运算
a = np.random.randint(70,90,10)
print(a)
result=[a>80]
print(result)

[73 72 71 75 77 88 71 85 79 79]
[array([False, False, False, False, False, True, False, True, False,
False])]
##np.where()实现数据筛选
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))

[[ 1.20479444 -1.24462666 1.11126117 1.37603328]
[-1.20093922 -0.14377739 -1.22836678 0.91405243]
[ 0.51444877 0.4666325 2.29990075 0.11391503]]
[[1.20479444 0. 1.11126117 1.37603328]
[0. 0. 0. 0.91405243]
[0.51444877 0. 2.29990075 0. ]]
[[1 0 1 1]
[0 0 0 1]
[1 0 1 0]]
统计计算a=np.random.randint(70,90,10).reshape(5,2)
print(a)
result=np.max(a,axis=0)
print(result)
result=np.min(a,axis=0)
print(result)
result=np.mean(a,axis=0)
print(result)

[[88 86]
[75 76]
[81 89]
[77 79]
[72 82]]
[88 89]
[72 76]
[78.6 82.4]
Pandas
Series数据结构
##1.创建Series对象
s=pd.Series([1,3,5,7,9,6,8])
print(s)

0 1
1 3
2 5
3 7
4 9
5 6
6 8
dtype: int64
##为地理位置创建Series对象
s1=pd.Series([1,1,1,1,1])
print(s1)
s2=pd.Series({‘longitude’:39,‘latitude’:116,‘temperature’:32})
print(s2[‘longitude’])
s3=pd.Series([3.4,0.8,2.1,0.3,1.5],range(5,10))
print(s3[6])

0 1
1 1
2 1
3 1
4 1
dtype: int64
39
0.8
访问Series数据对象
##修改数据
s2[‘city’]=‘beijing’
s2[‘longitude’]+=2
s2

longitude 41
latitude 116
temperature 32
city beijing
dtype: object
##按条件筛选数据
s3[s3>2]

5 3.4
7 2.1
dtype: float64
##增加成员对象
stiny=pd.Series({‘humidity’:84})
s4=s2.append(stiny)
s4

C:\Users\86152\AppData\Local\Temp\ipykernel_21348\820513047.py:3: FutureWarning: The series.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
s4=s2.append(stiny)

longitude 41
latitude 116
temperature 32
city beijing
humidity 84
dtype: object
##删除数据成员
s2=s2.drop(‘city’)
s2

longitude 41
latitude 116
temperature 32
dtype: object
DataFrame对象
##创建DataFranme对象
dict1={‘col1’:[1,2,5,7],‘col2’:[‘a’,‘b’,‘c’,‘d’]}
df=pd.DataFrame(dict1)
df

lista=[1,2,3,4]
listb=[‘a’,‘b’,‘c’,‘d’]
df=pd.DataFrame({‘col1’:lista,‘col2’:listb})
df

数组创建

a=pd.DataFrame([[1.1,1.4,1.7],[4,5,6],[11,13,45]],columns =[“t1”,“t2”,“t3”])
a

DataFrame对象
pd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=[‘a’,‘b’,‘c’,‘d’], columns=[‘1’,‘2’,‘3’,‘4’,‘5’])
print(pd)
print()
print(pd[‘1’])
print()
print(pd[‘1’][‘a’])

1   2   3   4   5

a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19

a 0
b 5
c 10
d 15
Name: 1, dtype: int32

0
fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=[‘a’,‘b’,‘c’,‘d’], columns=[‘1’,‘2’,‘3’,‘4’,‘5’])
print(fd.loc[[‘a’, ‘b’], [‘1’, ‘3’]])
print()
print(fd.iloc[0:1, 2:3])

1 3
a 0 2
b 5 7

3
a 2
修改DataFrame数据

##增加
fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=[‘a’,‘b’,‘c’,‘d’], columns=[‘1’,‘2’,‘3’,‘4’,‘5’])
fd[‘e’]=6
fd

1
2
3
4
5

fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=[‘a’,‘b’,‘c’,‘d’], columns=[‘1’,‘2’,‘3’,‘4’,‘5’])
print(fd)
print(fd.drop(columns=‘1’)) # 删除‘1’列, column代表待删除的列名
print(fd.drop(index=‘a’)) # 删除‘a’行,index代表待删除的行名
fd.drop(index=‘a’, axis=1, inplace=True) # 从原数据中删除数据,axis表示是删除一行还是删除一列
print(fd)

1   2   3   4   5

a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
2 3 4 5
a 1 2 3 4
b 6 7 8 9
c 11 12 13 14
d 16 17 18 19
1 2 3 4 5
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
1 2 3 4 5
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
数据对齐

加法

s1 = pd.Series({‘color’:1, ‘size’:2, ‘weight’:3})
s2 = pd.Series({‘color’:5, ‘size’:7, ‘weight’:4.5, ‘priec’: 1})
print(s1.add(s2, fill_value=0))

color 6.0
priec 1.0
size 9.0
weight 7.5
dtype: float64
##乘法
s1 = pd.Series({‘color’:1, ‘size’:2, ‘weight’:3})
s2 = pd.Series({‘color’:5, ‘size’:7, ‘weight’:4.5, ‘priec’: 1})
print(s1 * s2)

color 5.0
priec NaN
size 14.0
weight 13.5
dtype: float64
其他算数操作与此类似

缺失数据的处理:
data = pd.Series([1,2,None,4])
print(data.dropna(axis=0)) # 这里的axis是判断对行还是列进行过滤,这里是过滤列,如果想过滤行就将axis=1

dfHow = pd.DataFrame([[1,2,None], [None, None, None], [1,1,1]])
print(dfHow.dropna(axis=0, how=‘any’)) # how参数:any只要有None值就删除,all必须要一整行或者整列是None才删除
print()
print(dfHow.dropna(axis=0, how=‘all’))

0 1.0
1 2.0
3 4.0
dtype: float64
0 1 2
2 1.0 1.0 1.0

 0    1    2

0 1.0 2.0 NaN
2 1.0 1.0 1.0
Matplotlib
Matplotlib是python的一个基本2D绘图库,它提供了很多参数,可以通过参数控制样式、属性等

matplotlib.pyplot:

##绘制简单的plot图表
fig = plt.figure()
fig,axes=fig.subplots(2,3)

1
2
3
4

##绘制简单的plot图表
fig = plt.figure()
fig,axes=fig.subplots(2,3)

在这里插入图片描述

绘制图形
import matplotlib.pyplot as plt
fig = plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,3)
plt.show()

在这里插入图片描述import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
rect = plt.Rectangle((0.2,0.75), 0.4, 0.15, color=‘r’,alpha=0.3) # 创建一个长方形对象
ax.add_patch(rect) # 将图形添加到画布中,同理,其他的图形也是这样操作的,只是一些参数不同而已

<matplotlib.patches.Rectangle at 0x27203c10ac0>
在这里插入图片描述
plot函数
import matplotlib.pyplot as plt
import numpy as np

a = np.arange(0,10,1)
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.plot(a, a * 1.5, a, a * 2, a, a * a) # 里面的参数一共分为三组,((a, a * 1.5), (a, a * 2), (a, a * a))
plt.legend([‘1.5x’, ‘2.0x’, ‘x*x’])
plt.show()

在这里插入图片描述import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y, marker=‘o’)
plt.show()

在这里插入图片描述
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def randrange(n, randFloor, randCeil):
rnd = np.random.rand(n) # 生成n个随机数
return (randCeil - randFloor) * rnd + randFloor

plt.rcParams[‘font.sans-serif’]=[‘SimHei’] # 设置中文
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection=‘3d’) # 添加子3D坐标轴
n = 100
for zmin, zmax, c, m, l in [(4,15,‘r’,‘o’, ‘低值’), (13,40,‘g’,'', ‘高值’)]:
x = randrange(n, 0, 20)
y = randrange(n, 0, 20)
z = randrange(n, zmin, zmax)
ax.scatter(x, y, z, c=c, marker=m, label=l, s=z
6)

ax.set_xlabel(‘X-value’)
ax.set_ylabel(‘Y-value’)
ax.set_zlabel(‘Z-value’)

ax.set_title(‘高/低值3D散点图’, alpha=0.6, size=15, weight=‘bold’)
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值