zoukankan      html  css  js  c++  java
  • pandas进行条件格式化以及线性回归的预测

    条件格式化

    • 需求1:

      • 将三次考试的成绩小于60分的值找出来,并将字体变为红色
    • 需求2:

      • 将每次考试的第一名找出来,将背景变为绿色
    • 需求3:

      • 使用背景颜色的深浅来表示数值的大小
    • 需求4:

      • 使用数据条的长度表示数值的大小

    在这里我们需要用到两个函数apply和applymap

    apply和applymap的区别:

    apply是指根据轴进行匹配,从左往右是用轴为1即axis=1,从上至下是用轴为0即axis=0,默认是从上往下进行列匹配

    applymap是指无差别的进行指定区域匹配

    # 定义一个函数,如果分数少于60就变为红色(color:{color}将改变字体颜色)
    def low_score_red(s):
        color = 'red' if s<60 else 'black'
        return f'color:{color}'
    # 定义一个函数,每次考试的第一名变为绿色(background-color:lime将底部颜色变为绿色)
    def highest_score_green(col):
        return ['background-color:lime' if s == col.max() else 'background-color:white' for s in col]
    students = pd.read_excel('C:/Users/1/Downloads/Students.xlsx')
    students.style.applymap(low_score_red,subset=['Test_1','Test_2','Test_3']).apply(highest_score_green,subset=['Test_1','Test_2','Test_3'])
    

    gai

    Seaborn包:在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn就能做出很具有吸引力的图,而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充,而不是替代物。

    使用背景颜色的深浅来表示数值的大小

    import seaborn as sns
    # light_palette调色板
    color_map = sns.light_palette('green', as_cmap=True)
    students.style.background_gradient(color_map,subset=['Test_1','Test_2','Test_3'])
    

    gai

    使用数据条的占比表示数值的大小

    students.style.bar(color='orange',subset=['Test_1','Test_2','Test_3'])
    

    gai

    线性回归预测

    准备的数据如下图:

    gai

    import matplotlib.pyplot as plt
    sales = pd.read_excel('C:/Users/1/Downloads/Sales.xlsx',dtype={'Month':str})
    # 绘制散点图,以索引为x轴,以收益为Y轴
    plt.scatter(sales.index,sales.Revenue)
    # 将x轴刻度从索引改为年月,并将年月的方向旋转90°,rotation是旋转的意思
    plt.xticks(sales.index, sales.Month, rotation=90)
    # tight_layout是选择紧凑型图形的意思
    plt.tight_layout()
    plt.show()
    

    gai

    # 导入科学库,线性回归包
    from scipy.stats import linregress
    
    '''
    slope 代表斜率
    intercept 代表与Y轴的截点
    '''
    # 计算出斜率和截点根据索引与收益
    slope,intercept,r,p,std_err = linregress(sales.index,sales.Revenue)
    # 线性回归方程
    erp = sales.index*slope + intercept
    # 先绘制出散点图
    plt.scatter(sales.index, sales.Revenue)
    # 更改刻度
    plt.xticks(sales.index, sales.Month, rotation=90)
    # 绘制出直线
    plt.plot(sales.index, erp, color='red')
    # 修改标题名为线性方程
    plt.title(f'y={slope}*X+{intercept}')
    plt.show()
    

    gai

    根据此方程可以预测未来的收益,只需要将年月输入即可

  • 相关阅读:
    SCOM 初探 [SCOM应用系列之一]
    SCOM 安装部署 [SCOM应用系列之二]
    CMMI 配置管理(Configuration Management)系列(1) 简介
    设计模式总结之创建型设计模式
    tabbar图片渲染的问题
    react实现自定义hooks(节流和防抖)
    前端工程化5js源码编译和ast
    react实现自定义hooks(跑马灯)
    react实现自定义hooks(倒计时)
    react实现自定义hooks(移动端拖拽)
  • 原文地址:https://www.cnblogs.com/lishi-jie/p/10150318.html
Copyright © 2011-2022 走看看