<Python>/[DataFrame]

파이썬 Pandas DataFrame 저장(to_html)

9566 2023. 2. 21. 15:18
728x90

DataFrame.to_html(buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, justify=None, max_rows=None, max_cols=None, show_dimensions=False, decimal='.', bold_rows=True, classes=None, escape=True, notebook=False, border=None, table_id=None, render_links=False, encoding=None)

 

파이썬 Pandas DataFrame의 저장 방법 중 하나인 to_html 메서드에 대해 알아보겠습니다.

to_html() 메서드란?

to_html() 메서드는 DataFrame을 HTML 형식으로 출력해줍니다. DataFrame을 HTML 형식으로 출력함으로써, 데이터를 웹상에서 쉽게 볼 수 있도록 도와줍니다.

to_html() 메서드 사용 방법

to_html() 메서드는 매개변수로 다양한 인자를 받을 수 있습니다. 이 중 일부를 살펴보겠습니다.

index 인자

index 인자를 True로 설정하면 DataFrame의 인덱스를 출력합니다.

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [24, 26]})
print(df.to_html(index=True))
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Alice</td>
      <td>24</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Bob</td>
      <td>26</td>
    </tr>
  </tbody>
</table>

columns 인자

columns 인자를 True로 설정하면 DataFrame의 열 이름을 출력합니다.

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [24, 26]})
print(df.to_html(columns=True))
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Alice</td>
      <td>24</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Bob</td>
      <td>26</td>
    </tr>
  </tbody>
</table>

border 인자

border 인자를 설정하면 출력되는 테이블의 테두리의 굵기를 조절할 수 있습니다.

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [24, 26]})
print(df.to_html(border=2))
<table border="2" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Alice</td>
      <td>24</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Bob</td>
      <td>26</td>
    </tr>
  </tbody>
</table>
 

col_space 인자는 각 열(컬럼)의 너비를 조절하는 데 사용됩니다. 기본값은 None으로, 이 경우에는 모든 열의 너비가 동일하게 설정됩니다. col_space 인자에는 리스트 형태로 열의 너비를 지정할 수 있습니다. 예를 들어, [50, 100, 75]와 같이 지정하면 첫 번째 열의 너비는 50, 두 번째 열의 너비는 100, 세 번째 열의 너비는 75가 됩니다.

또한, na_rep 인자는 결측치(missing value)를 대체할 문자열을 지정합니다. 기본값은 None으로, 이 경우에는 결측치가 빈 문자열('')로 표시됩니다. na_rep 인자에는 문자열 값을 지정할 수 있습니다. 예를 들어, 'N/A'나 'NaN'과 같은 문자열을 지정하여 결측치를 대체할 수 있습니다.

마지막으로, border 인자는 표의 테두리 여부를 설정합니다. 기본값은 None으로, 이 경우에는 테두리가 없습니다. border 인자에는 True나 False 값을 지정하여 테두리 여부를 설정할 수 있습니다. 예를 들어, True로 설정하면 표에 테두리가 추가됩니다.

 

728x90