Pandas로 html 테이블을 읽는 방법(예제 포함)
pandas read_html() 함수를 사용하여 HTML 테이블을 pandas DataFrame으로 읽을 수 있습니다.
이 함수는 다음 기본 구문을 사용합니다.
df = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ')
다음 예는 이 함수를 사용하여 이 Wikipedia 페이지 에서 NBA 팀 이름 테이블을 읽는 방법을 보여줍니다.
예: Pandas로 HTML 테이블 읽기
read_html() 함수를 사용하기 전에 lxml을 설치해야 할 수도 있습니다:
pip install lxml
참고 : Jupyter 노트북을 사용하는 경우 이 설치를 수행한 후 커널을 다시 시작해야 합니다.
다음으로, read_html() 함수를 사용하여 이 Wikipedia 페이지 의 각 HTML 테이블을 읽을 수 있습니다.
import pandas as pd import numpy as np import matplotlib. pyplot as plt from unicodedata import normalize #read all HTML tables from specific URL tabs = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ') #display total number of tables read len (tabs) 44
이 페이지에서 총 44개의 HTML 테이블이 발견되었음을 알 수 있습니다.
관심 있는 테이블에 “Division”이라는 단어가 포함되어 있다는 것을 알고 있으므로 match 인수를 사용하여 이 단어가 포함된 HTML 테이블만 검색할 수 있습니다.
#read HTML tables from specific URL with the word "Division" in them
tabs = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ',
match=' Division ')
#display total number of tables read
len (tabs)
1
그런 다음 테이블 열의 이름을 나열 할 수 있습니다.
#define table
df = tabs[0]
#list all column names of table
list (df)
[('Division', 'Eastern Conference'),
('Team', 'Eastern Conference'),
('Location', 'Eastern Conference'),
('Arena', 'Eastern Conference'),
('Capacity', 'Eastern Conference'),
('Coordinates', 'Eastern Conference'),
('Founded', 'Eastern Conference'),
('Joined', 'Eastern Conference'),
('Unnamed: 8_level_0', 'Eastern Conference')]
처음 두 열에만 관심이 있으므로 다음 열만 포함하도록 DataFrame을필터링 할 수 있습니다.
#filter DataFrame to only contain first two columns
df_final = df. iloc [:, 0:2]
#rename columns
df_final. columns = [' Division ', ' Team ']
#view first few rows of final DataFrame
print ( df_final.head ())
Division Team
0 Atlantic Boston Celtics
1 Atlantic Brooklyn Nets
2 Atlantic New York Knicks
3 Atlantic Philadelphia 76ers
4 Atlantic Toronto Raptors
최종 테이블에는 “Division” 및 “Team” 열만 포함됩니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 파일 형식을 읽는 방법을 설명합니다.
Pandas로 텍스트 파일을 읽는 방법
Pandas로 Excel 파일을 읽는 방법
Pandas로 CSV 파일을 읽는 방법