python项目应用实例(四)用pandas将结果写入html表格之中

参考:https://blog.csdn.net/tz_zs/article/details/81137998

官方API文档:http://pandas.pydata.org/pandas-docs/version/0.19.0/generated/pandas.DataFrame.to_html.html

目录

一、创建表格

1.1 例程

二、写出结果

2.1 index

2.2 df

2.3 写入html文件

2.4 结果


一、创建表格

https://blog.csdn.net/tz_zs/article/details/81137998

1.1 例程

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
index = ["2018-07-01", "2018-07-02", "2018-07-03", "2018-07-04"]
df = pd.DataFrame(index=index)
df["一"] = [11, 12, 13, 14]
df["二"] = [21, 22, 23, 24]
print(df)
"""
             一   二
2018-07-01  11  21
2018-07-02  12  22
2018-07-03  13  23
2018-07-04  14  24
"""
 
axes_subplot = df.plot()
# print(type(axes_subplot)) #<class 'matplotlib.axes._subplots.AxesSubplot'>
plt.xlabel("time")
plt.ylabel("num")
plt.legend(loc="best")
plt.grid(True)
plt.savefig("test.png")
 
HEADER = '''
    <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
    '''
FOOTER = '''
        <img src="%s" alt="" width="1200" height="600">
        </body>
    </html>
    ''' % ("test.png")
with open("test.html", 'w') as f:
    f.write(HEADER)
    f.write(df.to_html(classes='df'))
    f.write(FOOTER)

二、写出结果

2.1 index

为左边一竖排,与df的key不一样。df中的元素与index一一对应

    def write_clases_result_into_html(self):
        print('writing result into html')
        index=[]
        for class_idx in range(self.class_num):
            index.append('class'+str(class_idx))
        df=pd.DataFrame(index=index)

2.2 df

其中的元素的个数必须与index的元素的个数一样。

比如这种写法就会出现报错

df['weight'],df['precision'],df['recall'],df['F1']=[],[],[],[]
'''
  File "badcase_analyse.py", line 180, in write_clases_result_into_html
    df['weight'],df['precision'],df['recall'],df['F1']=[],[],[],[]
  File "/home/xingxiangrui/chun-ML_GCN/env/lib/python3.6/site-packages/pandas/core/frame.py", line 3370, in __setitem__
    self._set_item(key, value)
  File "/home/xingxiangrui/chun-ML_GCN/env/lib/python3.6/site-packages/pandas/core/frame.py", line 3445, in _set_item
    value = self._sanitize_column(key, value)
  File "/home/xingxiangrui/chun-ML_GCN/env/lib/python3.6/site-packages/pandas/core/frame.py", line 3630, in _sanitize_column
    value = sanitize_index(value, self.index, copy=False)
  File "/home/xingxiangrui/chun-ML_GCN/env/lib/python3.6/site-packages/pandas/core/internals/construction.py", line 519, in sanitize_index
    raise ValueError('Length of values does not match length of index')
ValueError: Length of values does not match length of index
'''

所以我们先创建list再往里写

        weight_list,precision_list,recall_list,F1_list=[],[],[],[]
        # df['weight'],df['precision'],df['recall'],df['F1']=[],[],[],[]
        self.cls_P, self.cls_R, self.cls_F1,self.cls_weight
        for class_idx in range(self.class_num):
            weight_list.append(self.cls_weight[class_idx])
            precision_list.append(self.cls_P[class_idx])
            recall_list.append(self.cls_R[class_idx])
            F1_list.append(self.cls_F1[class_idx])
        df['weight']=weight_list
        df['precision']=precision_list
        df['recall']=recall_list
        df['F1']=F1_list

2.3 写入html文件

直接创建head与body,写入html文件

        df['weight']=weight_list
        df['precision']=precision_list
        df['recall']=recall_list
        df['F1']=F1_list
        HEADER = '''
            <html>
                <head>
                    <meta charset="UTF-8">
                </head>
                <body>
            '''
        FOOTER = '''
                </body>
            </html>
            '''
        with open(self.html_path, 'w') as f:
            f.write(HEADER)
            f.write(df.to_html(classes='df'))
            f.write(FOOTER)

2.4 结果

成功写入

三、例程

运算出王者荣耀护甲值与实际的伤害比例的关系

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
运算王者荣耀装备机制
"""
import numpy as np
import matplotlib.pyplot as plt
import math
import pandas as pd

################  1.实际伤害比例与护甲值计算
plt.figure(1)

# 比例显示与运算
AR=[]
AD_ratio=[]

AR_all=np.linspace(0,1500,10) # 0-1500之间的护甲值

for AR_item in AR_all:
    AR.append(AR_item)
    AD_ratio.append(602/(602+AR_item)*100)

# 画图显示
plt.plot(AR,AD_ratio,marker='o')
plt.xlim(0,1500)
plt.grid( color = 'blue',linestyle='-',linewidth = 0.3)
plt.ylim(0,100)

for a, b in zip(AR, AD_ratio):
    a=round(a,0) #规定一位精度
    b=round(b,1)
    plt.text(a, b, (a,b),ha='center', va='bottom', fontsize=10)

plt.title('护甲与AD伤害比例%', fontproperties="SimSun")
plt.xlabel('AR护甲', fontproperties="SimSun")
plt.ylabel('AD受到伤害比例', fontproperties="SimSun")
#plt.show()

# 表格显示

AR=[]
AD_ratio=[]
ratio_decrese=[]
AR_all=np.linspace(0,1500,10) # 0-1500之间的护甲值,第三个参数是值的数量
for AR_item in AR_all:
    AR.append(round(AR_item,0))
    AD_ratio.append(round(602/(602+AR_item)*100,2))
    ratio_decrese.append(round((602/(602+AR_item)-602/(602+AR_item+100))*100,2))
df = pd.DataFrame(index=AR)
df["AD_ratio"]=AD_ratio
df["ratio_decrese"]=ratio_decrese

HEADER = '''
    <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
    '''
FOOTER = '''
        <img src="%s" alt="" width="1200" height="600">
        </body>
    </html>
    '''
with open("C:\\Users\\xingxiangrui\Desktop\\照片\\test.html", 'w') as f:
    f.write(HEADER)
    f.write(df.to_html(classes='df'))
    f.write(FOOTER)

print("Program done!")

 

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祥瑞Coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值