728x90
반응형
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 1 15:51:57 2022
@author: KITCOOP
test0701_A.py
"""
'''
1. http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp 의 내용을
인터넷을 통해 데이터를 수신하고 다음 결과형태로 출력하시오.
결과는 현재 날씨에 따라 달라 질수 있습니다.
[결과]
+ 흐림
|- 서울
|- 인천
|- 수원
|- 파주
|- 이천
|- 평택
|- 대전
|- 세종
|- 홍성
|- 청주
|- 충주
|- 영동
|- 광주
|- 목포
|- 여수
|- 순천
|- 광양
|- 나주
|- 전주
|- 군산
|- 정읍
|- 남원
|- 고창
|- 무주
|- 대구
|- 안동
|- 포항
|- 경주
|- 울진
|- 울릉도
+ 구름많음
|- 춘천
|- 원주
|- 강릉
+ 흐리고 비
|- 부산
|- 울산
|- 창원
|- 진주
|- 거창
|- 통영
|- 제주
|- 서귀포
'''
from bs4 import BeautifulSoup #html, xml 분석 도구
import urllib.request as req #인터넷 접속 모듈
url="https://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp"
res = req.urlopen(url) # 인터넷(url)에 연결. 요청.
info = {} #dictionary. {"wf": ["city",...],"wf": ["city",...]}
# soup : res의 정보를 분석해서 저장 객체
soup = BeautifulSoup (res, "html.parser")
#find_all("location") : location 태그 정보들.
for location in soup.find_all("location") :
#location.find("city").string : location 태그의 하위 태그 중 city태그 선택
name = location.find("city").string #도시명
weather = location.find("wf").string #흐림, 맑음
if not (weather in info) : #새로운 날씨정보.
info[weather] = [] # 도시명을 저장하기 위한 리스트 객체 생성
info[weather].append(name)
# info 딕셔너리 정보 출력
for weather in info.keys() :
print("+",weather)
for name in info[weather] : # 리스트 출력
print(" |- ",name)
'''
2. chipotle.tsv 파일을 읽고 item 별 판매 갯수 시각화하기.
가장 많이 판매한 상품 10개만 막대그래프로 출력하기
20220701-2.png 참조
'''
import pandas as pd
import matplotlib.pyplot as plt
# sep : '\t' : 셀 구분이 ,가 아니므로 구분 문자 설정. \t : tab 설정
chipo = pd.read_csv("data/chipotle.tsv", sep = '\t')
chipo_chicken = chipo[chipo['item_name'] == "Chicken Bowl"]
# Chicken Bowl 상품의 전체 판매 수량 조회
chipo_chicken["quantity"].sum()
# 상품별 판매 갯수
item_qty = chipo.groupby("item_name")["quantity"].sum()
item_qty
# 수량의 합으로 내림차순 정렬
item_qty = item_qty.sort_values(ascending=False)[:10] #판매수량이 많은 10개 상품
item_qty
item_name_list = item_qty.index.tolist() #그래프 출력할 item이름 목록
sell_cnt = item_qty.values.tolist() #그래프 출력할 item 목록
# 그래프 출력
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1,1,1)
ax.bar(item_name_list, sell_cnt, align='center')
plt.ylabel('item_sell_count')
plt.xlabel('item Name')
ax.set_xticklabels(item_name_list, rotation=90)
plt.title('Distribution of all sell item')
plt.show()
plt.savefig("20220701-2.png",dpi=400,bbox_inches="tight")
'''
3. 멕시코풍 프랜차이즈 Chipotle의 주문 데이터를 이용하여 문제 풀기
Chicken Bowl을 2개 이상 주문한 주문 횟수 구하기
주문번호 Chicken Bowl 주문수량
1 2
2 3
3 1
주문횟수 : 2 1,2,번주문만 횟수
'''
import pandas as pd
chipo = pd.read_csv("data/chipotle.tsv", sep = '\t')
# chipo_chicken : 주문한 상품이 Chicken Bowl인 데이터 목록
chipo_chicken = chipo[chipo['item_name'] == "Chicken Bowl"]
chipo_chicken
# chipo_chicken 중 주문수량이 2개 이상인 데이터만 저장
chipo_chicken_result = chipo_chicken[chipo_chicken['quantity'] >= 2]
chipo_chicken_result
chipo_chicken_result.groupby("order_id").count()
len(chipo_chicken_result.groupby("order_id").count()) #행의 수
print(chipo_chicken_result.shape[0]) #행의 수
728x90
반응형
'study > Python' 카테고리의 다른 글
[Python] 44. drink.csv 파일 분석하기. annotate, CCTV_in_Seoul.csv, population_in_Seoul.xls 파일 분석하기, crime_in_Seoul.csv, 경찰관서 위치.csv 파일 분석하기 (0) | 2022.07.05 |
---|---|
[Python] 43. chipotle.tsv 파일 분석하기, drink.csv 파일 분석하기. 상관계수 (0) | 2022.07.04 |
[Python] 42. Test (0) | 2022.07.01 |
[Python] 42. BeautifulSoup : html,xml 태그 분석 모듈, 셀레니움, 이미지 다운 받기 (0) | 2022.07.01 |
[Python] 41. Test 답 (0) | 2022.06.30 |