본문 바로가기

Data/Python

(18)
Machine Learning #4 Pandas Pandas는 고수준의 자료구조와 파이썬을 통한 빠르고 쉬운 Series- 일련의 객체를 담을 수 있는 1차원 벡터- index(색인)라고 하는 배열의 데이터에 연관되 이름을 가지고 있다. import pandas as pd import numpy as np obj = pd.Series([-4,7,-4,3]) print('\n',obj, '\n') print('\n',obj.values, '\n') print('\n',obj.index, '\n') obj2 = pd.Series([-4,7,-4,3], index=['d','b','a','c']) print('\n',obj2, '\n') print('\n',obj2.index, '\n') print('\n',obj2['a'], '\n') obj2['d'] ..
Machine Learning #3 numpy Numpy 배열- 배열을 생성할 때는 효율성을 높이려고 배열을 데이터에 연결- python 내부적으로는 array를 지원하지 않는다.- numpy는 C로 구성되어 있으며, 리스트 형태의 python data를 C의 array type으로 만들어 준다. [Code]import numpy as np arr = np.arange(10) print('\n', arr) print('\n', arr[5]) print('\n', arr[5:8]) arr[5:8] = 12 print('\n', arr) arr_slice = arr[5:8] print('\n', arr_slice) arr_slice[1] = 12345 print('\n', arr) arr_slice[:] = 64 print('\n', arr) arr3d..
Machine Learning #2 python 1.여러분이 10일 작업에 대한 두 가지 급여 옵션을 제의 받았다고 가정하자 옵션1: 하루에 $100 지급옵셥2: 첫째 날에 $1, 둘째 날에 $2, 셋째 날에 $4등 매일 전일 급여의 두 배를 받음 두 가지 옵션 중에 어떤 경우가 좀 더 유리한 옵션인지 결정하라.이 때 Option1과 Option2라는 함수를 각각 생성하여 계산하여라. def main():## Compare salary options opt1 = option1() opt2 = option2() print("Option 1 = ${0:,.2f}.".format(opt1)) print("Option 2 = ${0:,.2f}.".format(opt2)) if opt1 > opt2: print("Option 1 pays better.") el..
Machine Learning #1 python 1.슈퍼마켓에서는 사과를 파운드당 $2.50에 판매한다. 입력 값으로 파운드와 현금을 받은 후에 해당 거래에 의한 거스름돈을 계산하여 표시하는 프로그램을 작성하라. 만약 현금이 부족하면 "당신을 $x.xx를 더 지불해야합니다."를 출력해야한다. 2. 저축 계정은 이자율과 복리 기간을 명시한다. 만약 예치 금액 P, 명시된 이자율 r, 연중 m회 복리로 적립된다고 할 때, 1년 후 계정의 잔금은 아래와 같다. 다른 복합 기간에 대한 이자율은 직접 비교 할 수 없다. APY의 개념은 이러한 비교를수행하는데 사용된다. 매년 m번 복리로 설정된 이자율 r에 대한 APY는 다음과 같다. 은행에서 제공하는 이자율을 비교하는 프로그램을 작성하고, 가장 바람직한 이자율을 결정하라 Enter annual rate of ..
파이썬 선(禪)(Zen of Python) 파이썬 디자인 원리라고 불리는 ‘젠 오브 파이썬’을 보면 파이썬이 추구하는 가치를 보다 자세히 알 수 있다. 파이썬 선(禪)(Zen of Python)아름다움이 추함보다 좋다.(Beautiful is better than ugly)명시가 암시보다 좋다.(Explicit is better than implicit.)단순함이 복잡함보다 좋다.(Simple is better than complex.)복잡함이 꼬인 것보다 좋다.(Complex is better than complicated.)수평이 계층보다 좋다.(Flat is better than nested.여유로운 것이 밀집한 것보다 좋다.(Sparse is better than dense.)가독성은 중요하다.(Readability counts.)특별한 ..
Python 강좌(5) 기존 XML문서에 코드 레벨에서 Tag 및 인자 추가 from bs4 import BeautifulSoup fp = open("song.xml")soup = BeautifulSoup(fp, "html.parser") chanElm = soup.find('channel')songElm = soup.new_tag('song', sname = 'sname4')titleElm = soup.new_tag('title')titleElm.string = 'title4'singerElm = soup.new_tag('singer')singerElm.string = 'singer4' songElm.append(titleElm)songElm.append(singerElm)chanElm.append(songElm)print(..
Python 강좌(4) 파일 입출력 def fileWrite(): fp = open("text.txt", "wt") fp.write('hello') fp.close() print('file write') fp = open("text.txt", 'r')rd = fp.read()fp.close()print(rd) List를 받아 저장하는 방법(List객체를 파일로 덤프뜸) import pickle #객체 시리얼 라이즈 def obWrite(): # myList = [10, 20, 30] myList = [{'name':'홍길동', 'age':20}, {'name':'이순신', 'age':30}] fp = open('ob.txt', 'wb') #코드 변형이 가해지면 안되기 때문에 바이너리로 읽는다. pickle.dump(myList..
Python 강좌(3) System Module 사용용법 sys.stdout.write('korea')sys.stdout.write('hello')print(sys.argv)print(sys.argv[0]) koreahello['E:\\study\\workspace\\pyTest\\day3\\r.py', 'aaa', 'abbbcccc', 'ccc']E:\study\workspace\pyTest\day3\r.py import time tm = time.localtime()# print(tm)s = "%d년%d월%d일" %(tm.tm_year, tm.tm_mon, tm.tm_mday)print(s) #323Pages1 = time.strftime("%Y-%m-%d %H-%M-%S")print(s1) 2016년7월20일2016-07..