dataframe으로 json이용

2021. 8. 19. 18:00python/pandas, numpy

728x90

CSV file => JSON file로 만들어보아요!

# 파일처리(후 저장)를 하려면 1. '파일을 open'
#                                     2. 파일에 내용을 써야해요!
#                                     3. 파일을 close

# with를 이용해 open만 하면 with 구문이 끝나면서 resource의 close가  자동으로 이루어진다

 

with open(파일 경로, 모드) as 파일 객체:
with open('./data/csv_to_json.json', 'w', encoding='utf-8') as f:

    #data/csv_to_json.json(파일명), 어떤용도이냐 'w'는 writing 'r'은 read

    # encoding을잡지않으면 중국,일본,한국어등 영어권을 제외하면 깨진다

    #  as는 별명을 붙이는것
    df.to_json(f, force_ascii=False, orient='columns')
    # json 데이터가 생성되고 column명이 json의 key값이 되요!

    # [참고] 파일명을 쓰지 않으면 저장은 되지 않고 출력만 된다.

 


# DataFrame 생성

import numpy as np
import pandas as pd

data = {'이름': ['아이유', '김연아', '홍길동'],
        '학과': ['컴퓨터', '수학과', '경영학과'],
        '나이': [25, 29, 30]}

df = pd.DataFrame(data)

display(df)

 


DataFrame을 json 파일로 저장해 보아요!

# with open('./data/student_json_column.json', 'w', encoding='utf-8') as f:
#     df.to_json(f, force_ascii=False, orient='columns')  # default

json formatter를 이용해 정리한다

전체가 하나의 json (컬럼명이 키  /  인덱스가 숫자)

 

 

# with open('./data/student_json_record.json', 'w', encoding='utf-8') as f:
#     df.to_json(f, force_ascii=False, orient='records')  # 

전체를 json배열 (list처럼 생김) / record한줄마다 json


# with open('./data/student_json_index.json', 'w', encoding='utf-8') as f:
#     df.to_json(f, force_ascii=False, orient='index')  # 

record와 비슷하며 key값이 index
    


with open('./data/student_json_values.json', 'w', encoding='utf-8') as f:
    df.to_json(f, force_ascii=False, orient='values')  # 
키값이 없이 값만 가져오며 배열형태 / 프로그램처리하기 편하다


 

 

# 위의 내용은 Pandas DataFrame의 정보를 JSON으로 변환시키는거예요!!

# JSON을 DataFrame으로 바꿀 수 있나요?
import numpy as np
import pandas as pd
import json

with open('./data/student_json_column.json', 'r', encoding='utf-8') as f:
    data_dict = json.load(f)

# 잘 생각해보면 JSON형식이 python의 dictionary와 유사
# print(data_dict)

df = pd.DataFrame.from_dict(data_dict, orient='columns')

from_dict 없이도 만들수 있으나 위4가지형식때문에 dic 로부터 dataframe을 만들거에요! 뒤에 orient를 줄수있다

display(df)

 


# Open API를 활용해서 JSON 데이터를 가져다가 DataFrame으로 만들어보아요!!

# 1. 필요한 module부터 import
import numpy as np
import pandas as pd
import json
import urllib         # python 자체 modul이며 open api를 가져올수 있다

 

 

# 2. 영화진흥위원회 Open API를 호출하기 위한 url이 있어야 해요!
#    이 url을 이용해서 서버프로그램을 호출해 보아요!


movie_url = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json'
query_string = '?key=629d53a9d31fcd5c14481b3797a7f22f&targetDt=20210801'

last_url = movie_url + query_string

result_obj = urllib.request.urlopen(last_url)             
# request요청
print(result_obj) 로 확인       # <http.client.HTTPResponse object at 0x00000173CBB10948>

 

result_json = result_obj.read()   # 문자열형태의 json데이터를 얻어와요!

result_dict = json.loads(result_json)  # json을 dict로 변환

print(result_dict)

 

 

 

 

# 우리가 원하는 DataFrame의 형태

# rank     title           salesAmt
# 1        랑종             '49559450'
# 2        은혼 더 파이널    '9303340'

# df = pd.DataFrame({
#     'rank' : [1, 2, ...],
#     'title': [랑종, 은혼 더 파이널, ...],
#     'salesAmt': ['49559450', '9303340', ...]
# })

 



rank_list = list()   # 빈 list를 하나 준비해요!
title_list = list()
sales_list = list()

for tmp in result_dict["boxOfficeResult"]['dailyBoxOfficeList']:
    rank_list.append(tmp['rank'])
    title_list.append(tmp['movieNm'])
    sales_list.append(tmp['salesAmt'])
    

 

#나온 값들을 dataframe으로 만든다
df = pd.DataFrame({
    'rank' : rank_list,
    'title': title_list,
    'salesAmt': sales_list
})    

display(df)

 

'python > pandas, numpy' 카테고리의 다른 글

pandas 공분산, 정렬  (0) 2021.08.21
pandas 인덱스 와 컬럼(index & colum)  (0) 2021.08.20
pandas 기초  (0) 2021.08.19
numpy 3일차  (0) 2021.08.18
numpy 정리  (0) 2021.08.18