pandas.to_csv 中文乱码问题
df.to_csv("predict_result.csv",encoding="utf_8_sig")
UTF-8以字节为编码单元,它的字节顺序在所有系统中都是一样的,没有字节序的问题,也因此它实际上并不需要BOM(“ByteOrder Mark”)。但是UTF-8 with BOM即utf-8-sig需要提供BOM。
在程序中能够正常输出中文,但是导出到文件后使用excel打开是出现中文乱码是因为excel能够正确识别用gb2312、gbk、gb18030或utf_8 with BOM 编码的中文,如果是utf_8 no BOM编码的中文文件,excel打开会乱码。
打印所在机器的内存大小
import psutil
def print_memory_size():
'''输出系统内存'''
mem = psutil.virtual_memory()
total = str(round(mem.total / 1024 / 1024 / 1024))
print('系统内存为 {} GB'.format(total))
print_memory_size()
让图片说中文
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
图片边缘背景色改为白色
plt.rcParams['figure.facecolor'] = 'white'
figsize
plt.rcParams['figure.figsize'] = (14.0, 14.0)
Pandas.DataFrame内存占用
def print_mem_usage(df):
mem = df.memory_usage().sum() / 1024 ** 2
print('The DataFrame takes up {:.3} MB'.format(mem))
# 解决DataFrame中某些列的内容特别长而被截断,但又需要能输出更多的内容以便查看的情况,这里的数值可以根据需要进行修改
pd.set_option('display.max_colwidth',300)
解析JSON
import json
data = {
'name': 'pengjunlee',
'age': 32,
'vip': True,
'address': {'province': 'GuangDong', 'city': 'ShenZhen'}
}
# 将 Python 字典类型转换为 JSON 对象
json_str = json.dumps(data)
print(json_str)
# {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}}
# 将 JSON 对象类型转换为 Python 字典
user_dic = json.loads(json_str)
print(user_dic['address'])
# {'province': 'GuangDong', 'city': 'ShenZhen'}
ROC曲线(二分类)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc # 计算roc和auc
def auc_curve(y,prob):
fpr,tpr,threshold = roc_curve(y,prob) # 计算真正率和假正率
roc_auc = auc(fpr,tpr) # 计算auc的值
plt.figure(figsize=(6, 4.5))
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.3f)' % roc_auc) # 假正率为横坐标,真正率为纵坐标做曲线
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc='lower right')
plt.show()