본문 바로가기

부스트캠프 AI Tech/Python

(12)
Pandas Pandas Panel datas numpy와 통합하여 빠름 Series DataFrame loc, iloc, drop, reset_index, fill_value, lambda, map, apply, applymap, replace Built-in function describe, unique, sort_values, corr, cov, corrwith, pd.options.display Groupby split -> apply -> combine groupby, hierarchical index, unstack, reset_index, swaplevel, sort_index, sort_values, get_group, aggregation, transform, filter Pivot column에 l..
Numpy Numerical Python 일반 list에 비해 빠르고 효율적 python의 list는 mem address를 저장하지만, ndarray는 값을 직접 저장 list는 값의 변경이 용이하고 ndarray는 속도가 빠름 C++, 포트란 등과 통합 가능 import numpy as np 국룰 하나의 data type만 넣을 수 있음 (dynamic typing x) a = [1, 2, 3] b = [3, 2, 1] a[0] is b[-1] # True a = np.array(a) b = np.array(b) a[0] is b[-1] # False shape : array의 dimension 반환 (tuple) 1d : (col,), 2d : (row, col), 3d : (channel, row, col)..
Data handling CSV(comma separate value) import csv reader = csv.reader(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) Regular Expression 010-1234-5678 ^\d{3}\-\d{4}\-\d{4}$ # ^숫자3-숫자4-숫자4$ 소스 보기 , Ctrl + Shift + C 누르고 클릭 - html 상에서 위치 검색 beautifulsoup from bs4 import BeautifulSoup soup = BeautifulSoup(books_xml, "lxml") sop.find_all("author") JavaScript Object Notation(JSON) {"employee" : [ {"firstNa..
Exception/File/Log handling Exception try: except: else: finally: raise (예외 정보) # 강제로 Exception 발생 assert 예외 조건 # 특정 조건을 만족하지 않을 시 예외 발생 File os module, pathlib module File os module, pathlib module Pickle - object 자체를 저장(binary file) import pickle f = open("filename.pickle", "wb") pickle.dump(obj,f) # write f = open("filename.pickle", "rb") obj = pickle.load(f) # read Log import logging logging.debug() # 개발 시 기록 logging.i..
Module Module built-in module 같은 위치에 있는 .py 파일을 import해서 사용 Package module을 모아 놓은 하나의 프로그램 __init__.py 파일로 초기화 해야 함(3.3+부터는 필수 x) Namespace import a as b from a import b 상대 경로로 호출 가능 Virtual Environment virtualenv, conda 등
Object Oriented Programming Class - Instance snake_case : 함수/변수명 CamelCase : class명 class ClassName(object): def __init__ (self, name, age): self.name = name # self = 생성된 instance self.age = age Mangling Inheritance - Super class의 attr, method를 Sub class가 물려 받음 Polymorphism - 같은 이름의 method를 다르게 구현(overriding, overloading) Visibility(Encapsulation) - Class 간 간섭/정보공유 최소화 Property decorator First-class object variable, parame..
Pythonic code Split & join str.split('sep') # sep 기준으로 split 없을 시 공백 기준 "joiner".join(sequential data) # data를 joiner와 함께 concat List Comprehension result = [i for i in range(10)] word_1 = "hello" word_2 = "world!" result = [i+j for i in word_1 for j in word_2] # nested for loop result = [[i+j for i in word_1] for j in word_2] # word_2가 먼저 loop 돎 Enumerate & Zip alist = ['a1', 'a2', 'a3'] blist = ['b1', 'b2',..
Data Structure Stack Last In First Out Queue First In First Out Tuple immutable한 list Set 중복 x, non-sequential union, intersection, difference Dict tuple(Key, Value) Collections built-in 구조 deque, Counter, OrderedDict, defaultdict, namedtuple Deque Linked list 지원 rotate, reverse, appendleft 등 가능 list보다 빠름 Ordered Dict 입력 순서를 보장하는 dict python 3.6이상부터는 기본 dict도 보장 default Dict default value를 지정가능한 dict key가 존재하지..