판다스에서 작업을 하다보면 결과물인 데이터프레임을 이메일, 웹사이트 등에 붙여넣고 싶을 때가 종종있습니다. 스크린 샷으로 붙여넣을 수도 있겠지만 HTML 테이블 태그를 삽입한다면 더 깔끔하고 보기 좋을겁니다.
이번 시간에는 DataFrame을 HTML 형식으로 변환시켜주는 메서드 to_html()에 대해 알아보겠습니다.
1. 데이터프레임을 HTML 테이블 태그로 변환하기
[In]
import pandas as pd
# 데이터프레임 샘플
df_sample = pd.DataFrame(
{'name': ['Kim', 'LEE', 'Park', 'Choi'],
'math': [88, 74, 72, 85],
'english': [80, 90, 78, 80]
})
# HTML로 변환하기
html = df_sample.to_html()
print(html)
[Out]
<table border="1" class="dataframe">
<thead>
<tr style="text-align: center;">
<th>name</th>
<th>math</th>
<th>english</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kim</td>
<td>88</td>
<td>80</td>
</tr>
<tr>
<td>LEE</td>
<td>74</td>
<td>90</td>
</tr>
<tr>
<td>Park</td>
<td>72</td>
<td>78</td>
</tr>
<tr>
<td>Choi</td>
<td>85</td>
<td>80</td>
</tr>
</tbody>
</table>
위의 태그 출력 결과입니다.
name | math | english | |
---|---|---|---|
0 | Kim | 88 | 80 |
1 | LEE | 74 | 90 |
2 | Park | 72 | 78 |
3 | Choi | 85 | 80 |
2. 열 이름 가운데 정렬하기
html = df_sample.to_html(justify='center')
name | math | english | |
---|---|---|---|
0 | Kim | 88 | 80 |
1 | LEE | 74 | 90 |
2 | Park | 72 | 78 |
3 | Choi | 85 | 80 |
left, right, center 등 설정이 가능합니다.
3. 인덱스 값 제거하기
html = df_sample.to_html(index=False, justify='center')
name | math | english |
---|---|---|
Kim | 88 | 80 |
LEE | 74 | 90 |
Park | 72 | 78 |
Choi | 85 | 80 |
-이 글은 아나콘다(Anaconda3)가 설치된 환경을 기준으로 작성되었습니다.