有序字典
from collections import OrderedDict
#输出时可记录输入顺序
f=OrderedDict()
f['a'] = 'py'
f['b'] = 'c'
f['c'] = 'c6++'
随机模块
random
from random import randint
randint(1,7)
choice
from random import choice
choice([0,1,2,3])
文件读写
# 报错时[gbk...] 加 encoding='utf-8'
with open(r'F:\git.txt',encoding='utf-8') as f:
#text1 = f.read() #全读取
text2 = f.readlines() #因为会加换行符,所以,打印时用rstrip()方法
for line in text2:
print(line.rstrip().split('\t'))
f.close()
#读取模式 ('r' )、写入模式 ('w' )、附加模式 ('a' )或让你能够读取和写入文件的模式('r+' )
with open(r'path','w',encoding='utf-8') as f:
f.write(text1)
字符替换方法
# replace() 方法
mes = 'a bb fsd'
mes.replace('a','b')
异常处理
# try-except
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
数据存储
# json模块
# json.dump 数据存储
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
#json.load 数据加载
with open(filename) as f_obj:
numbers1=json.load(f_obj)
计数
count()
绘图
基本要素
# matplotlib.pyplot
import matplotlib.pyplot as plt
squares = [1,4,9,16,25,36]
plt.plot(squares,linewidth=5)
plt.title('Squares',fontsize=24)
plt.xlabel('value',fontsize=14)
plt.ylabel('square of Value',fontsize=14)
plt.tick_params(axis='both', labelsize=14) #刻度样式
#可以指定输入输出绘图 edgecolor删除数据轮廓 c颜色 cmap颜色映射 s 点大小
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
#plt.scatter(x_values, y_values, c='red', edgecolor='none', s=40)
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues,edgecolor='none', s=40)
plt.axis([0,1100, 0,1100000])#坐标轴取值 (x0,x1,y0,y1 )
plt.show()
#第一个实参指定要以什么样的文件名保存图表,第二个实参指定将图表多余的空白区域裁剪掉
plt.savefig('squares_plot.png', bbox_inches='tight')
plt.figure(figsize=(10,6))#图像尺寸
plt.legend()
双y轴绘制 twinx() 方法
双y轴绘制 twinx() 方法
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x_axis, results['training']['B'], label='Train_RMSE ', linewidth='2',
marker='x', markevery=6,c='red')
ax1.plot(x_axis, results['valid_1']['B'], label='Test_RMSE', linewidth='2',
marker='^', markevery=6,c='cyan')
ax2 = ax1.twinx() #共享X轴
x_axis2 = np.arange(100, 0,-1)
ax2.plot(x_axis2, results['training']['A'], label='Train_l2 ', linewidth='2',
marker='o', markevery=6,c='green')
ax2.plot(x_axis2, results['valid_1']['A'], label='Test_l2', linewidth='2',
marker='v', markevery=6,c='darkorange')
ax1.set_ylim(0, 0.15)
ax2.set_ylim(0, 0.02)
ax1.set_ylabel('rmse')
ax2.set_ylabel('l2')
fig.legend(loc=1,bbox_to_anchor=(0.7,1), bbox_transform=ax1.transAxes)#图例合并
标签分类法
import numpy as np '''这条很重要!!!!否则np.where要报错'''
label = array(datingLabels)
idx_1 = np.where(label == 1)
idx_2 = np.where(label == 2)
idx_3 = np.where(label == 3)
p1 = plt.scatter(datingDataMat[idx_1,1], datingDataMat[idx_1,2],marker = 'x',color = 'm',label = 'not at all')
p2 = plt.scatter(datingDataMat[idx_2,1], datingDataMat[idx_2,2],marker = '+',color = 'c',label = 'in small doses')
p3 = plt.scatter(datingDataMat[idx_3,1], datingDataMat[idx_3,2],marker = 'o',color = 'r',label = 'in large doses')
plt.legend(loc = 'upper right')
plt.show()
动态矢量图
# 生成可缩放的矢量图形文件
import pygal
frequencies = [16,22,15,75,64,55]
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6', frequencies)
hist.render_to_file('a.svg') #渲染为svg文件 好看!
C color参数图
图像参考:https://blog.csdn.net/Koyurion/article/details/85857344