반응형
pandas를 이용해서 데이터의 양은 방대하므로 직접 만들지 않고 외부에서 가져오는 경우가 많다
csv
read_csv('file 경로')
첫 줄을 columns 명으로 데이터를 가져온다.
df = pd.read_csv('./data/student.csv')
Mysql
read_sql('sql', 'database')
외부모듈 pymysql이 필요하다
설치
conda install pymysql
# 또는
pip install pymysql
# 1. Database 연결
con = pymysql.connect(host = 'localhost',
user='root',
password='password',
db='database_name',
charset='utf8')
# 2. sql 작성
sql = 'SELECT bisbn, btitle, bauthor, bprice FROM book WHERE btitle LIKE "%java%"'
# 3. DataFrame 생성
df = pd.read_sql(sql, con)
위의 방법으로 sql 데이터를 불러올 수 있다.
json
read_json('json')
import numpy as np
import pandas as pd
import json # 내장 module
with open('./data/json/books.json', 'r', encoding='utf-8') as file :
dict_books = json.load(file)
df = pd.DataFrame(dict_books)
# df = pd.read_json(file)
# 위의 두 줄의 코드와 동일하게 작동한다.
df
Open API
urllib.request.urlopen('url')
json.loads()
import numpy as np
import pandas as pd
import urllib # api를 호출하기 위한 모듈
import json
api로 받아올 정보가 json이기 때문에 json 모듈이 필요하다.
영화진흥위원회의 일별 박스오피스 Open API를 이용해보겠다
key = 'keykeymykeytempkeyarbitarykey'
url = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json'
QueryString = '?key='+key+'&targetDt=20220316'
my_url = url + QueryString
load_page = urllib.request.urlopen(my_url) # => HTTPResponse object
my_dict = json.loads(load_page.read())
Open API로 불러온 데이터는 dataframe을 만들기 위한 적절한 모양이 아니고 API별로 형태가 제각각이기 때문에
dictionary로 불러온 데이터를 DataFrame에 맞게 가공한 후에 DataFrame으로 만들면 된다.
반응형
'Programming > Pandas' 카테고리의 다른 글
[pandas] read_csv 'utf-8' error (1) | 2022.03.21 |
---|---|
[Pandas] Movie Lens Data를 이용한 EDA 실습 (1) | 2022.03.21 |
[pandas] DataFrame Merge, Mapping, Grouping (0) | 2022.03.21 |
[pandas] DataFrame Indexing & Slicing (0) | 2022.03.17 |
[pandas] 데이터 조작 및 분석을 위한 python module - pandas (0) | 2022.03.17 |