728x90
반응형
SMALL

분류 전체보기 342

231127 Python 문제

[문제] 2006년도 홀수달에 입사한 사원들의 정보를 출력해주세요. c.execute('''select * from emp where date(hire_date) between date('2006-01-01') and date('2006-12-31') and strftime("%m", date(hire_date)) %2 != 0''') # 홀수달 c.fetchall() [문제] 년도별 입사한 인원수를 출력해주세요. c.execute("""select strftime('%Y', date(hire_date)), count(*) from emp group by strftime('%Y', date(hire_date))""") c.fetchall() # pandas식 으로 표현 years = pd.read_sql..

문제/Python 2023.11.27

231127 Python_sqlite3, transaction, data migration, 날짜, 형변환, cast()

■ sqlite #1. 별도의 DB SERVER 가 필요 없이 DB 파일 기초하여 데이터베이스를 처리하는 엔진 import sqlite3 sqlite3.version sqlite3.__file__ # 임시 저장 영역 구축(메모리) # 메모리생성 conn = sqlite3.connect(':memory:') # transaction 실행 conn c = conn.cursor() # sql문 실행메모리 영역 # sql하기 위한 실행, 문자형식으로 작성 c.execute('create table emp(id integer, name char, sal integer)') # 문자 insert 실행시, "" or ''. 단, insert문 을 ''으로 했다면, 문자입력할 때에는 ""으로 작성하는 것이 가장 bes..

Language/Python 2023.11.27

231127 Python 예외 사항, class, Except 상속

■ 예외사항 # 실행 중에 발생한 오류 def divide(x, y): return x/y divide(10, 2) divide(10, 3) divide(10, 0) # 예상이름: 예상메세지 / ZeroDivisionError: division by zero divide(10, "2") # 신텍스에러 = SyntaxError: invalid syntax. Perhaps you forgot a comma? divide(10, "2") # 타입에러 = TypeError: unsupported operand type(s) for /: 'int' and 'str' # try-except try: print(divide(10, 2)) # 실행중인 being절 except: # 정상적인 종료 print("오류가 발..

Language/Python 2023.11.27

231123 Python_상속, 다중상속, method, staticmethod, classmethod, cls

■ 상속 #1) 클래스의 메소드 속성을 물려받는다. #2) 공통된 내용을 하나로 묶어서 관리할 수 있다. # 부모 클래스 생성 class Parents: def __init__(self, name, pn): self.name = name self.pn = pn def show(self): print('이름 : {}, 전화번호: {}'.format(self.name, self.pn)) p = Parents('홍길동', '010-1000-0001') p.show() # 자식 클래스 생성 class Child(Parents): # Parents 클래스를 받아온다 def __init__(self, name, pn, addr, sn): self.name = name self.pn = pn self.addr = a..

Language/Python 2023.11.23

231123 Python_class, 인스턴스화, 인스턴스 변수, method

from pandas import Series, DataFrame import pandas as pd # class 생성 class Person: info = '' # instance 변수로 하는게 더 깔끔할 듯! def showinfo(self, name, age): # 형식매개변수 self.info += '이름 : {}, 나이 : {} \n'.format(name, age) # \n(엔터키) 은 print를 사용해야 효과 # man 인스턴스화 man = Person() #인스턴스화 man.info man.showinfo('홍길동', 30) man.info man.showinfo('박찬호', 20) # 추가 정보(누적) print(man.info) # woman 인스턴스화 woman = Person()..

Language/Python 2023.11.23

231122 Python 절차적(구조적) 지향 프로그램(procedural language), 객체지향프로그램(Object Oriented Language), Class 생성, 인스턴스변수, 인스턴스화

# ============================================================================= # 프로시저 프로그램 # = user1 result = 0 def add(arg): global result #result = result + arg result += arg add(10) result add(20) result # = user2 add(40) result result1 = 0 def add(arg): global result1 result1 += arg # user1, user2 에 add()에 영향을 미친다. # ex) 게임user 별로 아이템을 다른 user도 사용한다고 생각. # ==================================..

Language/Python 2023.11.22

231122 Python 문제

[문제] 년도 분기별 그룹형 막대그래프를 생성해주세요. df = pd.pivot_table(data = emp, index = emp['HIRE_DATE'].dt.year, columns = emp['HIRE_DATE'].dt.quarter, values = 'EMPLOYEE_ID', aggfunc = 'count') df.fillna(0, inplace=True) # ticks ='' 해결방안 → range() 범위 # 방법1) df.plot(kind='bar') plt.legend(labels= [ str(i)+'분기' for i in df.columns ], loc='upper left') plt.xticks(ticks = range(0,8), # 범위 labels= [ str(i)+'분기' for..

문제/Python 2023.11.22

231122 Python line plot(꺾은선그래프), 도수분포표(frequency table), histogram, box plot, 줄기 잎 그림(stem and leaf diagram), 산점도(scatter plot), folium

# 기본 import from pandas import Series, DataFrame import pandas as pd import matplotlib.pyplot as plt from matplotlib import font_manager, rc font_name = font_manager.FontProperties(fname='C:/Windows/Fonts/gulim.ttc').get_name() rc('font', family=font_name) import numpy as np # 색상 import import stemgraphic # 줄기 잎 그림 그래프 import folium # 지도 시각화 라이브러리 # 원하는 파일 read_csv 불러오기 emp = pd.read_csv('c:/dat..

Language/Python 2023.11.22

231121 Python 문제

[문제] 입사년도별 총액 급여를 출력해주세요 emp['SALARY'].groupby(emp['HIRE_DATE'].dt.year).sum() [문제] 입사요일별 인원수를 출력해주세요. 단, 한글요일로 출력해주세요 ('월화수목금토일'[0]+'요일') week = emp['EMPLOYEE_ID'].groupby(emp['HIRE_DATE'].dt.dayofweek).count() week.index Series(week.index).apply(lambda arg: '월화수목금토일'[arg]+'요일') week.index = Series(week.index).apply(lambda arg: '월화수목금토일'[arg]+'요일') week # 건수 출력 및 정렬 week = emp['HIRE_DATE'].dt.w..

문제/Python 2023.11.21
728x90
반응형
LIST