Python/Python Programming

[ Python ] pandas DataFrame을 HTML 형식으로 export 하기. (모니터링 활용)

Pydole 2023. 5. 17. 18:22

 

pandas의 to_html 메소드를 이용하여 DataFrame 결과를 HTML 형식으로 output

  


kor, math, eng 3개 컬럼의 기본 DataFrame 만들기

 

kor = [99, 53, 56, 56, 81, 90, 67, 68, 83, 55]
math = [91, 77, 59, 70, 100, 67, 89, 55, 93, 99]
eng = [96, 92, 92, 65, 51, 92, 55, 60, 54, 51]

import pandas as pd

df = pd.DataFrame(zip(kor,math,eng), columns=['kor','math','eng'])
df

 

 

html = df.to_html()
print(html)

 

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>kor</th>
      <th>math</th>
      <th>eng</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>99</td>
      <td>91</td>
      <td>96</td>
    </tr>
    <tr>
      <th>1</th>
      <td>53</td>
      <td>77</td>
      <td>92</td>
    </tr>
    <tr>
      <th>2</th>
      <td>56</td>
      <td>59</td>
      <td>92</td>
    </tr>
    <tr>
      <th>3</th>
      <td>56</td>
      <td>70</td>
      <td>65</td>
    </tr>
    <tr>
      <th>4</th>
      <td>81</td>
      <td>100</td>
      <td>51</td>
    </tr>
    <tr>
      <th>5</th>
      <td>90</td>
      <td>67</td>
      <td>92</td>
    </tr>
    <tr>
      <th>6</th>
      <td>67</td>
      <td>89</td>
      <td>55</td>
    </tr>
    <tr>
      <th>7</th>
      <td>68</td>
      <td>55</td>
      <td>60</td>
    </tr>
    <tr>
      <th>8</th>
      <td>83</td>
      <td>93</td>
      <td>54</td>
    </tr>
    <tr>
      <th>9</th>
      <td>55</td>
      <td>99</td>
      <td>51</td>
    </tr>
  </tbody>
</table>

 

 


 

HTML파일로 생성해 보자. ( test.html )

 

 

 

df.to_html('test.html')

 

 

 

만약, test.html 파일로 계속 갱신하여 모니터링 하려하면 아래와 같이 첫 line에 refresh 태그를 추가해 준다.

 

text = '<meta http-equiv="refresh" content="10" >\n'

with open("test.html", "r+") as f:
    s = f.read()
    f.seek(0)
    f.write(text + s)

 

 


 

특정 컬럼만 필터

 

html = df.to_html(columns=['kor'])

 

 


컬럼 열 크기 변경

 

html = df.to_html(col_space=[100,100,200])

 

 

 

 


 

최대 출력 수 지정

 

html = df.to_html(max_rows=2)

 

 

 

 

 

 

Document : https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html

 

pandas.DataFrame.to_html — pandas 2.0.1 documentation

next pandas.io.formats.style.Styler.to_html

pandas.pydata.org