재원's 블로그

Order & Find outliers(주문과 이상치 찾기) 본문

Python

Order & Find outliers(주문과 이상치 찾기)

KimJ.W 2023. 1. 23. 19:24

최초 작성일 : 2021-12-21
categories: Python


python을 활용해 'restaurant,order' 와 'covid' 데이터를 이용해서

'이상치 찾기' 를 실습 해 보았다.

# /c/Program Files/Anaconda3/python/envs/python-test
# -*- conding: utf-8 -*-

class Comments:
    title     = "#### %s 레스토랑에 오신걸 환영합니다. ####"

    product_description  = "%s:%s(%s원)"

    insert_price         = "\n요금을 넣어 주세요. : "

    insufficient_price    = "%s 요금이 부족합니다. 거스름돈은 %s원 입니다."

    select_menu          = "원하시는 메뉴를 선택하세요."

    select_error         = "잘못 입력하셨습니다."


    finish_sale          = "선택하신 %s 입니다. 거스름돈은 %s원 입니다.\n감사합니다."
    terminate_sale       = "주문을 종료합니다."

class Menus:
    food_names  = []
    food_prices = []
# /c/Program Files/Anaconda3/python/envs/python-test
# -*- conding: utf-8 -*-

from restaurant import Comments, Menus

all_menus = [
            {"menu": "김밥", "price": 1500},
            {"menu": "떡볶이", "price": 1800},
            {"menu": "우동", "price": 2000},
            {"menu": "라면", "price": 2500}
        ]

class Order(Menus):
    # class attribute 
    _data = all_menus
    _name = "김밥천국"
    _status = True

    def __init__(self):
        print(Comments.title %self._name)

    def set_products(self):
        Menus.food_names  = []
        Menus.food_prices = []
        for food in self._data:
            Menus.food_names.append(food["menu"])
            Menus.food_prices.append(food["price"])

    def run(self):
        self.set_products()
        while self._status:
            try:
                inputMoney = int(input(Comments.insert_price))
            except ValueError:
                print(Comments.select_error)
            else:
                self.selectMenu(inputMoney)

    def selectMenu(self, money):
        print(Comments.select_menu)
        for idx, name in enumerate(Menus.food_names):
            price = Menus.food_prices[idx]
            print(Comments.product_description %(str(idx), name, price))
        inputFood = int(input(Comments.select_menu))
        self.payment(money, inputFood)

    def payment(self, money, idx):
        name = Menus.food_names[idx]
        price = Menus.food_prices[idx]
        if money >= price:
            balance = money - price
            print(Comments.finish_sale %(name, str(balance)))
        else:
            print(Comments.insufficient_price %(name, str(money)))

if __name__ == "__main__":
    order = Order()
    try:
        order.run()
    except KeyboardInterrupt:
        order._status = False
        print(Comments.terminate_sale)

<실행 화면>

"C:\Program Files\anaconda3\python.exe" "C:/Program Files/anaconda3/envs/python-P/python-test/order.py"
#### 김밥천국 레스토랑에 오신걸 환영합니다. ####

요금을 넣어 주세요. : 1500
원하시는 메뉴를 선택하세요.
0:김밥(1500원)
1:떡볶이(1800원)
2:우동(2000원)
3:라면(2500원)
원하시는 메뉴를 선택하세요.0
선택하신 김밥 입니다. 거스름돈은 0원 입니다.
감사합니다.

요금을 넣어 주세요. : 

이런 식으로 가격을 입력하고 메뉴를 번호로 선택하면

해당 메뉴를 선택했다는 것과 거스름돈을 계산해서 출력해 주는

코드이다.

다음은 '결측치 찾기' 코드이다.

<결측치 확인>

import pandas as pd
covidtotals = pd.read_csv("data/covidtotalswithmissings.csv")
covidtotals.head()

<실행 화면>

missing value1

  • 일부 feature 에서 Missing Values 확인
covidtotals.info()

<실행 화면>

missing value2

  • 리스트 작성
    ● 인구통계 관련 column
    ● Covid 관련 column
    case_vars = ["location", "total_cases", "total_deaths", "total_cases_pm", "total_deaths_pm"]
    demo_vars = ["population", "pop_density", "median_age", "gdp_per_capita", "hosp_beds"]
    
    ["location"] + demo_vars
    
    covidtotals[demo_vars].isnull().sum(axis = 0) # column별로 결측치를 측정
    
    <실행 화면>

missing value3

covidtotals[case_vars].isnull().sum(axis = 0) # column별로 결측치를 측정

missing value4

  • 행 방향으로 발생한 결측치 확인
    demovars_misscnt = covidtotals[demo_vars].isnull().sum(axis = 1)
    demovars_misscnt.value_counts()
    
    <실행 화면>

missing value5

covidtotals[case_vars].isnull().sum(axis = 1).value_counts()

<실행 화면>

missing value6

  • 인구통계 데이터가 3가지 이상 누락된 국가를 나열하기
    ["location"] + demo_vars
    
    <실행 화면>

missing value7

covidtotals.loc[demovars_misscnt >= 3, ["location"] + demo_vars].T

<실행 화면>

missing value8

  • case 누락 국가 확인
    casevars_misscnt = covidtotals[case_vars].isnull().sum(axis = 1)
    casevars_misscnt.value_counts()
    
    <실행 화면>

missing value9

covidtotals.loc[casevars_misscnt == 2, ["location"] + case_vars].T

<실행 화면>

missing value10

covidtotals[covidtotals['location'] == "Hong Kong"]

<실행 화면>

missing value11

temp = covidtotals.copy()
temp

<실행 화면>

missing value12

temp[case_vars].isnull().sum(axis = 0)

<실행 화면>

missing value13

temp.total_cases_pm.fillna(0, inplace = True)
temp.total_deaths_pm.fillna(0, inplace = True)
temp[case_vars].isnull().sum(axis = 0)

<실행 화면>

missing value14

'Python' 카테고리의 다른 글

Missing value2 (결측치2)  (0) 2023.01.23
Missing value (결측치)  (0) 2023.01.23
Trees - Decision Tree about(결정 트리에 대해)  (0) 2023.01.23
python_step02,03,04  (0) 2023.01.23
class  (2) 2023.01.21