一、python基本语法
import math
print(math.pi)
print('The quick brown fox', 'jumps over', 'the lazy dog')
print(300+10)
# name=input()
# print(name)
# name = input('please enter your name: ')
# print('hello,', name)
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
print(3 * "un" + "ium")
ss = [5, 6, 9, 4, 10]
print(ss[2], len(ss))
print()
a = 0
while a < 5:
print('a =', a, end=',')
a = a+1
print('hello,%s' % 'world')
# list
classmate = [1, 2, 3, 4, 5, 6, 7, 8, 9]
classmate[-2] = 10
classmate.pop(5)
classmate.append(16)
classmate.insert(2, 33)
print(classmate)
# tuple
classmate2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(classmate2)
# 可变参数
def count(*numbers):
sum = 0
for number in numbers:
sum += number
print(sum)
# 关键字参数(传入字典)
def information(name, **extra):
if 'city' in extra:
h = extra.get('city')
print('city:', h)
# 循环、条件、字典
classmates = ['John', 'Tom', 'Mike']
students = ([1.75, 80.5], [1.65, 50], [1.72, 54])
bmi = []
for student in students:
bmi.append(student[1]/(student[0]**2))
print("\n", bmi)
i = 0
score = []
while i < len(bmi):
i = i+1
print('student%d:' % i)
if bmi[i-1] < 18.5:
score.append('过轻')
print("过轻")
elif bmi[i-1] > 18.5 and bmi[i-1] < 25:
score.append('正常')
print("正常")
else:
score.append('肥胖')
print("肥胖")
# dict
dic = {'John': score[0], 'Tom': score[1], 'Mike': score[2]}
print('John:', dic['John'])
print('Tom:', dic['Tom'])
print('Mike:', dic['Mike'])
# 如果key不存在,可以返回None,或者自己指定的value
print(dic.get('Mike', -1))
print(dic.get('Mke'))
# 删除字典元素
dic.pop('John')
print(dic.get('John'))
print(dic)
# dict的key必须是不可变对象。
# 这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了
# 所以list不可以作为key
# set
s = set([1, 2, 3])
s.add(4)
s.remove(2)
print(s)
count(100, 1546)
information('Tom', city='Shantou',)
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
s = Student('Jimmy', 95)
type(123)
# isinstance(h, Husky) #object -> Animal -> Dog -> Husky
print(s.name, s.score)
del s.name # 如果删除实例的name属性
#print (s.name,s.score)
i = 'a'+1
二、numpy
import numpy as np
array = np.array([[1, 2, 3],
[4, 5, 6]], dtype=np.int)
# 1.常用函数
print(array)
print(array.shape)
print(array.ndim) # 维度
print(array.dtype)
print(array.sum(axis=1)) # 1:行 0:列 等效写法:np.sum(array,axis=1)
print(array.max(axis=0))
print(array.min(axis=0))
array2 = np.zeros((3, 4))
array2 = np.ones((3, 4))
array2 = np.empty((3, 4))
print(array2)
A = np.array([[1, 2, 3],
[4, 5, 6]])
print(A.mean(dtype=int)) # 均值
# 老版本
print(np.average(A, axis=1)) # 均值,无法使用另外一种形式
print(np.median(A)) # 中位数,无法使用另外一种形式
print(np.cumsum(A)) # 累加
print(np.diff(A)) # 累差
print(np.sort(A))
print(np.clip(A, 5, 7)) # 取值区间为【5,7】
# 有序数列,左闭右开
for i in range(1, 10):
print(i, end=' ')
print('\n')
array3 = np.arange(1, 10)
print(array3)
# reshape
array4 = np.arange(12).reshape((3, 4)) # 0-11
print(array4)
array4 = np.linspace(1, 10, 6).reshape((2, 3))
print(array4)
# [[ 1. 2.8 4.6]
# [ 6.4 8.2 10. ]]
array5 = np.linspace(1, 10, 6).reshape(3, 2)*np.sin(10)
print(array5)
# 2.矩阵按位相乘VS矩阵乘法
print(array4*array4)
print(np.dot(array4, array5))
print(array4.dot(array5))
# 3.索引(得到位置)
A = np.array([[10, 2, 3],
[4, 5, 6]])
print(A.argmin())
print(A.argmax())
print(A[1][1])
print(A[1,:])
print(A[:,1])
print(A[1,1:3])
#将矩阵转换为一维列表
print(A.flatten())#列表
for i in A.flat:#A.flat是迭代器
print(i)
# 转置
print(np.transpose(A))
print(A.T)
#4.矩阵的合并与分割
print(np.vstack((A,A)))#上下合并
print(np.hstack((A,A)))#左右合并,注意参数是元组
print(np.vsplit(A,2))#上下分割
print(np.hsplit(A,3))#左右分割
#5.深拷贝和浅拷贝
A = np.array([[10, 2, 3],
[4, 5, 6]])
B=A#引用,指向同一个地址,浅拷贝
C=A.copy()#开辟新的内存空间,深拷贝
print(B)
print(C)
三、pandas
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
array1=pd.Series([1,5,98,99,92])
print(array1)
df=pd.DataFrame(np.arange(12).reshape((3,4)),index=[1,2,3],columns=['a','b','c','d'])
#增加序列
df['e']=pd.Series([1,2,3],index=[1,2,3])
print(df)
print(df.describe())
#排序
print(df.sort_index(axis=1,ascending=False))
print(df.sort_values(by='c'))
#选择:1.按标签 2.按位置
print(df.loc[:,['a','b']])
print(df.loc[1,['a','b']])
print(df.iloc[1:3,3])
#筛选
print(df[df.a>4])
#更改
df.iloc[2,2]=0
print(df)
df.a[df.a<8]=11
print(df)
#画图
df.plot()#plot methods:bar,list,box,kde,area,scatter......
#df.scatter()
plt.show()
#丢失数据处理
df.iloc[1,1]=np.nan
print(df)
print(df.dropna(axis=0,how="any"))#1个nan就舍去这一行,“all":所有是nan才舍去这一行
print(df.fillna(value=0))
print(df.isna())
#pandas合并 :concat,merge
# res=pd.concat([df1.df2],axis=0,ignore_index=True)
# res=pd.concat([df1,df2],axis=0,join="inner",ignore_index=True)#默认join="outer"
# res=pd.concat([df1,df2],axis=0,join_axes=[df1.index],ignore_index=True)#默认join="outer"
# res=pd.merge(df1,df2,on=['a''b'],how="inner")
四、matplotlib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(0, 10, 20, dtype=float)
print(x)
y1 = 11*x-10
y2 = 2*x*x-100
plt.figure(figsize=(15, 8), facecolor='white')
plt.xticks(x)
plt.yticks([60, 70, 80, 90, 100],
['just ok', 'a little bad', 'a little good', 'good', 'very good'])
# 坐标轴
plt.xlabel('x')
plt.ylabel('y')
#gca='get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 注解
l1, = plt.plot(x, y1, label='up')
l2, = plt.plot(x, y2, color='red', linestyle='--',
linewidth=4, label='down')
plt.legend(handles=[l1, l2], labels=[
'y1 = 11*x-10', 'y2 = 2*x*x-100'], loc='best')
plt.show()
# 注解
# plt.annotate()
# plt.text()
# 散点图:正态分布
plt.figure(figsize=(15, 8), facecolor='white')
n = 1024
X1 = np.random.normal(0, 1, n)
Y1 = np.random.normal(0, 1, n)
plt.scatter(X1, Y1, s=75, c='blue', alpha=0.5)
plt.xlim((-3, 3))
plt.ylim((-2, 2))
plt.xticks(())
plt.yticks(())
plt.show()
# 柱状图
plt.figure(figsize=(15, 8), facecolor='white')
n = 20
X2 = np.arange(20)
Y2 = np.random.uniform(0, 10, n)*X2
plt.bar(X2, Y2, facecolor='blue', edgecolor='white')
for x, y in zip(X2, Y2):
plt.text(x, y, "%.2f" % y, ha='center', va='bottom')
#gca='get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.xlabel('x')
plt.ylabel('y')
plt.xlim((0, 20))
plt.ylim((0, 200))
plt.show()
# image图片
# plt.imshow(...)
# plt.colorbar()
# 3D数据
fig = plt.figure(figsize=(15, 8), facecolor='white')
ax = Axes3D(fig, facecolor='pink')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
ax.set_zlim((-2, 2))
plt.show()
#分格显示
plt.subplot(2,2,1)
plt.plot(X2,Y2)
plt.subplot(2,2,2)
plt.scatter(X2,Y2)
plt.subplot(2,2,3)
plt.bar(X2,Y2)
plt.subplot(2,2,4)
X, Y = np.meshgrid(X2, Y2)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)
plt.contourf(X,Y,Z,zdir='z',cmap='rainbow')
plt.tight_layout()#Automatically adjust subplot parameters to give specified padding.
plt.show()
#另外三种方法:
#法一:
import matplotlib.gridspec as gridspec
plt.figure()
gs=gridspec.GridSpec(2,3)
ax1=plt.subplot(gs[0,:])
plt.plot(X2,Y2)
ax2=plt.subplot(gs[1,0])
plt.scatter(X2,Y2)
ax3=plt.subplot(gs[1,1])
plt.bar(X2,Y2)
ax4=plt.subplot(gs[1,2])
X, Y = np.meshgrid(X2, Y2)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)
plt.contourf(X,Y,Z,zdir='z',cmap='rainbow')
plt.tight_layout()
plt.show()
#法二:
# plt.subplot2grid()
#法三:
# plt.subplots()
python丰富学习资源:
https://space.bilibili.com/243821484/video?tid=0&keyword=&order=pubdate