[ํฌ๋กค๋ง] Web์์ Tabular data ์์ง
์น์์ ํ ์ด๋ธ ๋ฐ์ดํฐ๋ฅผ ์ง์ Python์ผ๋ก ์คํฌ๋ฉํ๊ณ ์ถ์ ๊ฒฝ์ฐ์ ์ฌ์ฉํ ์ ์๋ ๋ฐฉ๋ฒ์ ๋๋ค!
์ค์ต
์ํคํผ๋์์ "๋ํต๋ น ์ ๊ฑฐ ๊ฒฐ๊ณผ" ํ๋ฅผ ์๋ก ๋ค์ด๋ณด๊ฒ ์ต๋๋ค.
https://en.wikipedia.org/wiki/Politics_of_Pennsylvania
Politics of Pennsylvania - Wikipedia
Politics of a U.S. state Pennsylvania has swung from being a Republican-leaning state during much of the 20th century to being a notable battleground state in presidential elections. Pennsylvania backed the Democratic presidential candidate in every electi
en.wikipedia.org
ํ์ด์ง์ ์ ์ํ์ ๋ ๊ฐ์ ธ์ค๊ณ ์ํ๋ ํ๋ "Presidential election results"์ ๋๋ค!
1. ์น๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
import pandas as pd
import numpy as np
table_PA = pd.read_html('http://en.wikipedia.org/wiki/Politics_of_Pennsylvania')
2. Presidential elecction results๋ง ์ถ์ถ
len(table_PA) #ํ์ด์ง์ 5๊ฐ์ ํ
์ด๋ธ์ด ์์(table_PA)->์ฐ๋ฆฌ๋ ์ด ์ค์ ๋์ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ์ ธ์ค๊ณ ์ถ์
table_PA = pd.read_html('http://en.wikipedia.org/wiki/Politics_of_Pennsylvania', match='Presidential election results') #๋์ ๊ฒฐ๊ณผ์ ์ผ์นํ๋ ํ
์ด๋ธ๋ง ๊ธ์ด์ด
len(table_PA) #๋ฐํ๋ ๊ฐ์ 1๋ก ํ๋์ ํ
์ด๋ธ๋ง ์ผ์นํ๋ค๋ ์๋ฏธ!
df=table_PA[0]
* table_PA์ ํํ๋ ๋ค์๊ณผ ๊ฐ์ผ๋ฏ๋ก table_PA[0]์ df์ ์ ์ฅํด์ค๋ค!
-> df.head๋ฅผ ํตํด 5๊ฐ์ ํ๋ง ํ์ธํด๋ณด๋ฉด ์ ์์ง๋ ๊ฒ์ ํ์ธํ ์ ์๋ค!
3. ์ ์ฒ๋ฆฌ (์ซ์๋ก ๋ณํ)
๋ถ์์ ์ํด์๋ ๊ฐ์ numericํํ๋ก ๋ฐ๊ฟ์ค์ผํ๋๋ฐ ๊ฐ์ %๊ฐ ์์ด .apply(pd.to_numeric)ํจ์๋ฅผ ์ ์ฉํ๊ธฐ ํ๋ค๋ค..!
๋ฐ๋ผ์ "%"์ ๊ฑฐ๋ฅผ ๋จผ์ ์ ํํ ํ์ ํจ์๋ฅผ ์ ์ฉํด์ฃผ์ด์ผ ํจ!
df.head()
df.info() #ํ์ธํด๋ณด๋ฉด ์ซ์๊ฐ ์๋๋ผ ๋ฌธ์๋ก ๋์ด์๊ธฐ ๋๋ฌธ์ ๋ฐ๊ฟ์ค
#"%"๋ฌธ์ ์ ๊ฑฐ
df['Democratic']=df['Democratic'].str[:4] #Democratic์ ์์ 4๊ธ์๋ง ์ถ์ถํด๋ผ, %๊ธธ์ด๊ฐ ๋ค ๋๊ฐ๊ธฐ ๋๋ฌธ์ ๊ฐ๋ฅํ์ผ์
df['Republican']=df['Republican'].str[:4]
df[['Democratic', 'Republican']]=df[['Democratic','Republican']].apply(pd.to_numeric)
df.info()
4. ๋ฐ์ดํฐ๊ฐ ์ ๋ฐ๋๊ฒ์ ํ์ธํ ์ ์๋ค!
->