from pandas import DataFrame from Data import grade_dic from print_df import print_df # 데이터 프레임 df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 특정 조건 행 조회 search_index = df.query('국어 > 70') # 출력 print_df(search_index)
session = requests.Session() #현재 세션의 referer 페이지를 '없음'으로 강제 설정 # → referer : 이전에 머물렀던 페이지 주소 # → referer 값이 없으면 웹 서버는 브라우저에서 직접 URL을 입력한 것으로 간주한다 #현재 세션의 웹 브라우저 정보(User-agent)를 구글 크롬으로 설정 session.headers.update({"referer": None, "User-agent": user_agent}) #특정 웹 페이지에 접속 # → headers 파라미터로 가져올 컨텐츠의 형식을 미리 지정해 놓는다 r = session.get(naver_news_url) #가져온 HTML 코드 확인 # → 웹 페이지의 인코딩 형식을 확인하여 설정해야 한다 r.encoding = "euc-kr" print_df(r.text) #데이터 전처리(1) - HTML을 분석하여 원하는 영역 추출 #웹 페이지의 소스코드 HTML 분석 객체로 생성 soup = BeautifulSoup(r.text, "html.parser") #CSS 선택자를 활용하여 가져오기를 원하는 부분 지정 selector = soup.select("#articleBodyContents") print_df(selector) #데이터 전처리(2) - 추출된 영역 안에서 불필요한 태그 제거 for item in selector: for target in item.find_all("script"): target.extract() #찾아낸 태그 삭제
from pandas import DataFrame from Data import grade_dic from print_df import print_df # 데이터 프레임 df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 다중 조건 행 조회 # or 조건 all_index = df.query('국어 < 50 or 영어 < 40') # 출력 print_df(all_index)
# /section11/11-refine2.py # 데이터정제(2) - 결측치 대처법 from print_df import print_df from pandas import DataFrame from sample import grade_dic import numpy # pip install sklearn from sklearn.impute import SimpleImputer df = DataFrame(grade_dic, index=["철수", "영희", "민철", "수현", "호영"]) print_df(df) #------------------------------------------------------------------------------- # 결측치를 특정값으로 채움 # -> sklearn 모듈이 아닌 DataFrame 자체 기능 re_df1 = df.fillna(value=50) print_df(re_df1) #------------------------------------------------------------------------------- # sklearn 모듈 기반으로 결측치 대처 # 1) 결측치를 정제할 규칙 정의 # -> 각 열단위로 평균(strategy="mean")을 결측치(missing_values)에 지정 # -> strategy 옵션 : mean=평균, median=중앙값, most_frequent : 최빈값(가장 많이 관측되는 수) imr = SimpleImputer(missing_values=numpy.nan, strategy="mean") # 2) dataframe의 값에 대해 규칙 적용 df_imr = imr.fit_transform(df.values) print_df(df_imr) # 3) 적용된 규칙으로 새로운 데이터 프레임 생성
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) df['프로그래밍'] = [92, 49, 21, 20, None] # print_df(df) # 슬라이싱 사용 삭제 column_del = df.drop(df.columns[2:4], axis=1) print_df(column_del)
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) # 결측치 확인 null_data = df.isnull() null_data2 = df.isna() print_df(null_data) print_df(null_data2)
df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 점수 이상치 필터링 filtering_outlier = df.query('국어 > 100') filtering_outlier2 = df.query('과학 > 100') # 필터링 된 이상치 인덱스 추출 filtering_outlier_index = list(filtering_outlier.index) filtering_outlier_index2 = list(filtering_outlier2.index) # 결측치로 변경 for i in filtering_outlier_index: df.loc[i, '국어'] = numpy.nan for j in filtering_outlier_index2: df.loc[j, '과학'] = numpy.nan # 결측치 규칙 정의 null_regulation = SimpleImputer(missing_values=numpy.nan, strategy='most_frequent') # 규칙 적용 df_null_regulation = null_regulation.fit_transform(df.values) # 데이터 프레임 생성 df2 = DataFrame(df_null_regulation, index=list(df.index), columns=list(df.columns)) print_df(df2)
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) # 다른 데이터 프레임 병합 # 제외된 열 -> NaN(결측치) # sort -> 열을 이름순으로 정렬(기본값 : true) df2 = DataFrame({'국어': 34, '수학': 40, '과학': 90}, index=['짱구']) new_df = df.append(df2, sort=False) print_df(new_df)
import pandas from pandas import DataFrame from matplotlib import pyplot from print_df import print_df kobis_key = "8c56c13266968c52f489661f44b76b5b" kobis_api = "http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=%s&targetDt=%s" today = dt.datetime.now() delta = dt.timedelta(days=-1) yesterday = today + delta yesterday_str = yesterday.strftime("%Y%m%d") api_url = kobis_api % (kobis_key, yesterday_str) print_df(api_url) r = requests.get(api_url) if r.status_code != 200: print("[$d Error] %s" % (r.status_code, r.reason)) quit() r.encoding = "utf-8" result = json.loads(r.text) print_df(result) df = DataFrame(result['boxOfficeResult']['dailyBoxOfficeList']) print_df(df.head()) df = df.filter(items=['movieNm', 'audiCnt'])
# /section11/11-refine3.py # 데이터정제(3) - 이상치 정제 from print_df import print_df from pandas import DataFrame from sklearn.impute import SimpleImputer from sample import grade_dic import numpy df = DataFrame(grade_dic, index=["철수", "영희", "민철", "수현", "호영"]) print_df(df) #------------------------------------------------------------------------------ # 국어점수에 대한 이상치 필터링 r = df.query("국어 > 100") print_df(r) # 필터링 된 이상치 데이터에 대한 인덱스 추출 r_index = list(r.index) print_df(r_index) # 이상치를 갖는 인덱스에 대한 국어 점수를 결측치로 변경 for i in r_index: df.loc[i, "국어"] = numpy.nan print_df(df) # 결측치를 정제할 규칙 정의 -> 결측치에 대한 평균점수 imr = SimpleImputer(missing_values=numpy.nan, strategy="mean") # 2) dataframe의 값에 대해 규칙 적용
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) null_data = df.isnull() # 결측치 수 파악 null_data_sum = null_data.sum() print_df(null_data_sum)
from pandas import DataFrame from Data import grade_dic from print_df import print_df # 데이터 프레임 df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 열, 행 이름 변경 df_c_i = df.rename(columns={ '국어': 'kor', '영어': 'eng', '수학': 'math', '과학': 'sin' }, index={ '노진구': 'no', '이슬이': 'is', '비실이': 'bs', '퉁퉁이': 'tt', '도라에몽': 'dr' }) # 열, 행 이름 변경 후 출력 print_df(df_c_i)
charset='utf8') # Connection 으로부터 Cursor 생성 curs = conn.cursor(pymysql.cursors.DictCursor) # SQL문 실행 sql = 'SELECT COUNT(DATE_FORMAT(start_day, "%y-%m")) AS count, DATE_FORMAT(start_day, "%y-%m") AS month FROM schedule GROUP BY DATE_FORMAT(start_day, "%y-%m") ORDER BY DATE_FORMAT(start_day, "%Y-%m") ASC LIMIT 0 , 11;' curs.execute(sql) # 데이터 Fatch rows = curs.fetchall() conn.close() data = DataFrame(rows) print_df(data) # 한글폰트 설정 및 그래프 크기 설정 pyplot.rcParams['font.family'] = 'NanumGothic' pyplot.rcParams["font.size"] = 16 pyplot.rcParams['figure.figsize'] = (12, 8) pyplot.figure() pyplot.title('월별 출발일정 수') pyplot.plot(data['count'], label='여행출발 일정', linestyle='-', marker='.', color='#ff6600') pyplot.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], data['month']) pyplot.grid()
import os import requests from print_df import print_df from sample import image_url from sample import user_agent session = requests.Session() session.headers.update({'referer': None, 'User-agent': user_agent}) r = session.get(image_url, stream=True) if r.status_code != 200: print("%d 에러가 발생했습니다. " % r.status_code) quit() fname = os.path.basename(image_url) print_df(fname) p = fname.rfind(".") if p < 0: fname += ".jpg" print_df(fname) img = r.raw.read() with open(fname, 'wb') as f: f.write(img)
from pandas import DataFrame from Data import grade_dic from print_df import print_df # 데이터 프레임 df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 열 순서 변경 df_columns = df.reindex(columns=['국어', '수학', '영어', '과학']) # 열 순서 변경 후 출력 print_df(df_columns)
from crawler import Crawler from print_df import print_df from pandas import DataFrame import pandas as pd import urllib df = DataFrame() keyword = '노트북' params = {"query": keyword, "frm": "NVSHATC"} query = urllib.parse.urlencode(params) site_url = "https://search.shopping.naver.com/search/all.nhn?" + query print_df(site_url) crawler = Crawler() html = crawler.select(site_url, selector=".info") for item in html: info = {} title_list = item.select('.tit') title = title_list[0].text.strip() info['제품명'] = title price_list = item.select('.num') price = price_list[0].text.strip() price = price.replace(",", "") price = int(price) info['가격'] = price spec_list = item.select('.detail a')
names = pd.concat(df_pieces, ignore_index=True) # 가장 많이 작명한 이름들 - 이름의 트렌드 # ascending=False -> 내림차순 def get_top100(group): return group.sort_values(by='born', ascending=False)[:100] # 연도 / 성별을 기준으로 그룹화 후 출력 grouped = names.groupby(['year', 'gender']) top100 = grouped.apply(get_top100) top100.reset_index(inplace=True, drop=True) total_born_name = top100.pivot_table('born', index='year', columns='name', aggfunc=sum) subset = total_born_name[['Mary', 'Anna', 'John', 'William']] boys = top100[top100.gender == 'M'] girl = top100[top100.gender == 'F'] df_boy = boys[boys.year == 1900] print_df(df_boy)
# /section11/13-graph.py # 데이터프레임 시각화 from matplotlib import pyplot from print_df import print_df from pandas import DataFrame from sklearn.impute import SimpleImputer from sample import traffic import numpy df = DataFrame(traffic) print_df(df) #------------------------------------------------- # 데이터 전처리 month = list(df["month"]) # "월"에 대한 컬럼만 리스트로 추출 new_name = {} # 빈 딕셔너리 생성 print_df(month) # "월" 리스트에 대해 반복 for i, v in enumerate(month): # 딕셔너리에 {인덱스번호 : 값} 형식으로 채워넣음 new_name[i] = v # 데이터프레임의 인덱스 변경 df.rename(index=new_name, inplace=True) # 기존의 "월" 컬럼은 삭제 df.drop("month", axis=1, inplace=True) print_df(df) #------------------------------------------------- # 한글폰트, 그래픽 크기 설정 pyplot.rcParams["font.family"] = "NanumGothicCoding"
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) # 행 삭제(결과 반영된 복사본 생성) del_df = df.drop('노진구') print_df(del_df)
from print_df import print_df from pandas import read_csv from pandas import DataFrame from sklearn.impute import SimpleImputer import numpy import datetime as dt from matplotlib import pyplot # 데이터 수집 df = read_csv("data/grade.csv", encoding="euc-kr") print(df.shape) print_df(df.head(5)) #데이터 전처리 student_list = list(df['이름']) index_dict = {} for i, v in enumerate(student_list): index_dict[i] = v df.drop('이름', axis=1, inplace=True) df.rename(index=index_dict, inplace=True) print_df(df.head(5)) #데이터 정제 #열별로 결측치(빈칸)의 수를 파악 print_df(df.isnull().sum())
#/section11/10-refine1.py #데이터 정제(1) #결측치(Missing value) : 누락된 값, 비어있는 값 #이상치(Outlier) : 정상 범주에서 크게 벗어난 값 from print_df import print_df from pandas import DataFrame from sample import grade_dic df = DataFrame(grade_dic, index=["철수", "영희", "민철", "수현", "호영"]) print_df(df) #결측치 여부 확인 : isnull(), isna() 둘 중 아무거나 사용 # → 각 열에 대해 결측치가 아닐 경우 False, 결측치는 True로 표시 empty = df.isnull() empry = df.isna() print_df(empty) empty_sum = empty.sum() print_df(empty_sum) #결측치가 있는 모든 행 삭제 # → 원본은 변화 없음, 삭제 결과 리턴됨 na1 = df.dropna() #결측치가 삭데된 데이터 프레임 확인 print_df(na1) """ <class 'pandas.core.series.Series'> 국어 0
columns={ 'manufacturer': '제조회사', 'model': '모델명', 'displ': '배기량', 'year': '생산년도', 'cyl': '실린더개수', 'trans': '변속기종류', 'drv': '구동방식', 'cty': '도시연비', 'hwy': '고속도로연비', 'fl': '연료종류', 'class': '자동자종류' }, inplace=True ) # print_df(df) # 평균연비 합격을 의미하는 '연비테스트'컬럼을 mpg 데이터에 추가 # 평균연비 20이상이면 '합격', 그렇지 않으면 '불합격' # 도시연비, 고속도로 연비를 활용하여 평균연비 데이터 avg을 mpg 데이터에 추가 df['연비테스트'] = np.where((df['도시연비'] + df['고속도로연비']) / 2 >= 20, '합격', '불합격') # print_df(df.head(10)) # 각 값별로 수량을 카운트하여 새로운 데이터 프레임 생성 count = df['연비테스트'].value_counts() count_df = DataFrame(count) print_df(count_df) # --------------------------------------------------------- # 데이터 정제 # --------------------------------------------------------- # 결측치 여부 확인 empty_sum = df.isnull().sum() # print_df(empty_sum) # --------------------------------------------------- # 데이터 시각화 # --------------------------------------------------- # 그래프 만들기 plt.rcParams["font.family"] = 'NanumGothic' # 한글 폰트 지정(나눔고딕) plt.rcParams["font.size"] = 14 # 그래프 폰트 사이즈(14) plt.rcParams["figure.figsize"] = (10, 10) # 그래프 사이즈(10 x 10)
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) # 결측치 모든 행 삭제 null_data_del = df.dropna() print_df(null_data_del)
#/section11/13-graph.py #데이터프레임 시각화 from matplotlib import pyplot from print_df import print_df from pandas import DataFrame from sklearn.impute import SimpleImputer from sample import traffic import numpy df=DataFrame(traffic) print_df(df) """ +----+-------+-------+-------+--------+-------+ | | seoul | busan | daegu | inchun | month | +----+-------+-------+-------+--------+-------+ | 0 | 3166 | 927 | 933 | 655 | 1월 | | 1 | 2728 | 857 | 982 | 586 | 2월 | | 2 | 3098 | 988 | 1049 | 629 | 3월 | | 3 | 3172 | 955 | 1032 | 669 | 4월 | | 4 | 3284 | 1014 | 1083 | 643 | 5월 | | 5 | 3247 | 974 | 1117 | 627 | 6월 | | 6 | 3268 | 1029 | 1076 | 681 | 7월 | | 7 | 3308 | 1040 | 1080 | 657 | 8월 | | 8 | 3488 | 1058 | 1174 | 662 | 9월 | | 9 | 3312 | 971 | 1163 | 606 | 10월 | | 10 | 3375 | 958 | 1146 | 641 | 11월 | | 11 | 3179 | 982 | 1135 | 663 | 12월 | +----+-------+-------+-------+--------+-------+ """
from print_df import print_df import numpy df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) df['프로그래밍'] = [92, 49, 21, 20, None] # print_df(df) # numpy 사용열 추가 # sum : 합계 / mean : 평균 / max : 최대값 / min : 최소값 # astype('int') -> mean의 값을 정수로 df['평균'] = df.mean(axis=1).astype('int') # 다중 조건부 데이터 추가 # 학점 조건 gpa = [ (df['평균'] >= 90), # A (df['평균'] >= 80), # B (df['평균'] >= 70), # C (df['평균'] >= 59), # D (df['평균'] < 58), # F ] # 학점 gpa_label = ['A', 'B', 'C', 'D', 'F'] # 학점 추가 df['학점'] = numpy.select(gpa, gpa_label) print_df(df)
from pandas import DataFrame from Data import grade_dic from print_df import print_df df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # print_df(df) null_data_del = df.dropna() # 결측치 갯수 확인 print_df(null_data_del.isnull().sum())
# pip install xlrd # pip install openpyxl from print_df import print_df from pandas import ExcelFile from pandas import DataFrame from matplotlib import pyplot import datetime as dt # 엑셀파일 읽기 xls_file = ExcelFile('section12/children_house.xlsx') # 엑셀의 sheet 이름들 표시 sheet_names = xls_file.sheet_names print_df(sheet_names) # 첫 번째 sheet를 dataframe으로 변환 df = xls_file.parse(sheet_names[0]) print_df(df) #----------------------------------------------------- # 데이터 전처리 # 이름에 대한 열을 리스트로 추출 city_list = list(df["지역"]) print_df(city_list) # 새로 적용할 인덱스 이름에 대한 딕셔너리 구조 생성 index_dict = {} for i, v in enumerate(city_list): index_dict[i] = v
#모듈 설치 # pip install xlrd #pip install openpyxl from print_df import print_df from pandas import ExcelFile from pandas import DataFrame from matplotlib import pyplot import datetime as dt #엑셀파일 읽기 xls_file=ExcelFile("section12/children_house.xlsx") #엑셀의 sheet 이름들 표시 sheet_names=xls_file.sheet_names print_df(sheet_names) #<class 'list'> ['데이터', '메타정보'] #첫 번째 sheet를 dataframe으로 변환 df=xls_file.parse(sheet_names[0]) print_df(df) """ +----+----------+-------+-------+-------+ | | 지역 | 2014 | 2015 | 2016 | +----+----------+-------+-------+-------+ | 0 | 전국(계) | 43742 | 42517 | 41084 | | 1 | 서울 | 6787 | 6598 | 6368 | | 2 | 부산 | 1957 | 1971 | 1937 | | 3 | 대구 | 1588 | 1539 | 1483 | | 4 | 인천 | 2308 | 2278 | 2231 | | 5 | 광주 | 1260 | 1264 | 1238 | | 6 | 대전 | 1698 | 1669 | 1584 |
import requests import json from print_df import print_df simple_json_url = "http://itpaper.co.kr/demo/python/phone.json" r = requests.get(simple_json_url) if r.status_code != 200: print("[$d Error] %s" % (r.status_code, r.reason)) quit() r.encoding = "utf-8" print_df(r.text) result = json.loads(r.text) print_df(result) print("결과코드: %s" % result['rt']) print("결과메시지: %s" % result['rtmsg']) print("제품병: %s" % result['item']['name']) print("제조사: %s" % result['item']['type']) print("사진: %s" % result['item']['img']) print("정가: %s" % result['item']['price']['fixed']) print("판매가: %s" % result['item']['price']['sale'])
from pandas import DataFrame from Data import grade_dic from print_df import print_df from matplotlib import pyplot from sklearn.impute import SimpleImputer import numpy df = DataFrame(grade_dic, index=['노진구', '이슬이', '비실이', '퉁퉁이', '도라에몽']) # 국어점수 이상치 필터링 filtering_outlier = df.query('국어 > 100') # 필터링 된 이상치 인덱스 추출 filtering_outlier_index = list(filtering_outlier.index) print_df(filtering_outlier_index)