관리 메뉴

보리차

02) 데이터형 변환 - 딕셔너리, JSON, 집합, matplotlib 본문

공부/데이터 분석

02) 데이터형 변환 - 딕셔너리, JSON, 집합, matplotlib

보리콩 2021. 8. 31. 19:08

딕셔너리(dictionary)

{key: value}

key: 값을 찾기 위해 넣어 주는 데이터

value: 찾고자 하는 데이터

 

empty_dict = {}
new_dict = {'apple': '사과', 'book': '책'}
new_dict['human'] = '사람'	# 값 추가

 

딕셔너리는 원하는 값을 빠르게 찾을 수 있다.

딕셔너리의 키: 키로 넣을 수 있는 값에 제한이 있다.

# {[ID, 비밀번호]: 계정 정보}
kdhong = ['kdhong', 'cantcalldad']
accounts = {
	kdhong: ('Kildong Hong', ...),
}
kdhong[0] = 'kdhong.elice' # 키 값을 변형하면 x

=> 파이썬은 변하지 않는 값 만을 key값으로 받을 수 있다.

즉 key에는 리스트가 아닌 튜플이 와야한다.

 

# {id: 이름}
accounts = {
	"kdhong": "Kildong Hong",
}
print("kdhong" in accounts)	# True
print("elice" in accounts)	# False

 

딕셔너리 순회하기

accounts = {
	"kdhong": "Kildong Hong",
}
for username, name in accounts.items():
	print(username + " - " + name)

 

JSON: JavaScript Object Notation

웹 환경에서 데이터를 주고 받는 가장 표준적인 방식

키를 이용하여 원하는 데이터만 빠르게 추출 가능

데이터가 쉽게 오염되지 않음

다른 포맷에 비해 용량이 조금 큰 편

 

JSON과 딕셔너리 변환

loads( ): JSON -> 딕셔너리

dumps( ): 딕셔너리 -> JSON

# json 패키지를 임포트합니다.
import json

#JSON 파일을 읽고 문자열을 딕셔너리로 변환합니다.
def create_dict(filename):
    with open(filename) as file:
        json_string = file.read()
        return json.loads(json_string)


#JSON 파일을 읽고 딕셔너리를 JSON 형태의 문자열로 변환합니다.
def create_json(dictionary, filename):
    with open(filename, 'w') as file:
        json_string = json.dumps(dictionary)
        file.write(json_string)
        
        
src = 'netflix.json'
dst = 'new_netflix.json'

netflix_dict = create_dict(src)
print('원래 데이터: ' + str(netflix_dict))

netflix_dict['Dark Knight'] = 39217
create_json(netflix_dict, dst)
updated_dict = create_dict(dst)
print('수정된 데이터: ' + str(updated_dict))

 

 

집합(set)

중복이 없다

순서가 없다

# 셋 다 같은 값
set1 = {1, 2, 3}
set2 = set([1, 2, 3])
set3 = {3, 2, 3, 1}

 

원소 추가/삭제

num_set = {1, 3, 5, 7}
num_set.add(9)
numset.update([3, 15, 4])	# 여러 원소 추가
num_set.remove(7)		# 존재하지 않는 원소를 삭제하면 error
num_set.discard(13)		# 원소가 존재하지 않으면 무시

 

집합 다루기

num_set = {1, 3, 5, 7}
print(6 in num_set)	# False
print(len(num_set))	# 4

 

집합 연산

set1 = {1, 3, 5, 7}
set2 = {1, 3, 9, 27}

union = set1 | set2		# 합집합
intersection = set1 & set2	# 교집합
diff = set1 - set2		# 차집합
xor = set1 ^ set2		# XOR

 

 

 

그래프 다루기

matplotlib으로 그래프 설정

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

from elice_utils import EliceUtils
elice_utils = EliceUtils()

# 날짜 별 온도 데이터를 세팅합니다.
dates = ["1월 {}일".format(day) for day in range(1, 32)]
temperatures = list(range(1, 32))

# 막대 그래프의 막대 위치를 결정하는 pos를 선언합니다.
pos = range(len(dates))

# 한국어를 보기 좋게 표시할 수 있도록 폰트를 설정합니다.
font = fm.FontProperties(fname='./NanumBarunGothic.ttf')

# 막대의 높이가 빈도의 값이 되도록 설정합니다.
plt.bar(pos, temperatures, align='center')

# 각 막대에 해당되는 단어를 입력합니다.
plt.xticks(pos, dates, rotation='vertical', fontproperties=font)

# 그래프의 제목을 설정합니다.
plt.title('1월 중 기온 변화', fontproperties=font)

# Y축에 설명을 추가합니다.
plt.ylabel('온도', fontproperties=font)

# 단어가 잘리지 않도록 여백을 조정합니다.
plt.tight_layout()

# 그래프를 표시합니다.
plt.savefig('graph.png')
elice_utils.send_image('graph.png')

 

 

 

 

 

 

 

 

 

 

 

 

[출처: 앨리스AI트랙 2기 aitrack.elice.io]

'공부 > 데이터 분석' 카테고리의 다른 글

06) Pandas 심화  (0) 2021.09.05
05) Pandas  (0) 2021.09.03
04) NumPy  (0) 2021.09.02
03) 복잡한 형태의 데이터: csv, lambda, map, filter  (0) 2021.08.31
01) 데이터 분석에 필요한 파이썬 문법  (1) 2021.08.30