분석 Python/구현 및 자료(105)
-
[ Python ] 파일 폴더 관리시 자주 사용하는 것
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ # copy file shutil.copyfile( from , to ) # copy folder shutil.copytree(from , to ) # delete file or folder shutil.rmtree(file path , ignores_erros= True) # move file shutil.move( from path , to path ) # 파일 존재 여부 os.path.isfile( path ) # config 간단 사용 config = configparser.RawConfigParser() config.add_section("name") config.set("name" , "tag1" , somethin..
2019.10.31 -
[ Python ] Gmail로 메일 보내기
먼가 돌아가는 것에 대해서 error 같은 것을 빨리 체크하기 위해서 logging 작업을 하긴 하지만, 다른 작업과 병행을 하다보면 확인하기가 어려울 때가 있어서, 시간을 낭비할 우려가 있다. 그래서 이런 문제를 해결 하기 위해 에러가 날 때 메일을 보내주면, 더 쉽게 파악할 수 있지 않을까 생각을 했다. 그래서 오늘에서야 자료를 찾고 시도해봤다! 역시 파이썬에서는 이미 구현이 되어 있어서 참 편하게 아래 방법을 잘 따라 하니 바로 되었다! 일단은 구글 메일로 보내는 것을 할 예정이고, 구글 아이디에서 해줘야하는 것이 있다. 네이버도 된다고 하니, 아래 medium url을 눌러서 해보시면 된다! 구글 계정 로그인 -> 보안 -> 보안 수준이 낮은 앱으로 엑세스를 사용 나의 보안을 주고 편리함을 얻자 ..
2019.10.26 -
[ Python ] Loop ProgressBar 구현물
Python에서 Loop를 돌릴 때 유용한 ProgressBar 구현체 여기다가 먼가 중간 값으로 보고 싶을 때 함수에 추가하면 Loop마다 쌓여서 보이지 않고 그대로 보여줌. def printProgress(iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 50): formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) filledLength = int(round(barLength * iteration / float(total))) bar = '#' * filledLength + '-' * (barLe..
2019.10.23 -
[ Python] 한 리스트 안에 있는 중복 dict 제거하기
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ import json def remove_dupe_dicts(l): list_of_strings = [json.dumps(d, sort_keys=True) for d in l ] list_of_strings = set(list_of_strings) return [json.loads(s)for s in list_of_strings] def remove_dupe_dicts(l): return [dict(t) for t in {tuple(d.items()) for d in l}] data = [ {"id": 1, "sub": {"id": 1}}, {"id": 1, "sub": {"id": 2}}, {"id": 4}, {"id": 1..
2019.10.21 -
[ Python ] logging level name 추가 및 color 넣기
우연히 다른 거 찾다가, log에 색깔을 먹인다길래, 신기해서 해보니, 해보고 공유ㅎ log도 set level도 예전에 했던 방식보다 더 쉽게 할 수 있는 것도 있었다. import logging from colorlog import ColoredFormatter ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = ColoredFormatter( "%(log_color)s[%(asctime)s] %(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'white,bold', 'INFOV': 'cyan,bold', 'WARNING': 'yellow', ..
2019.09.29 -
__pycache__ 폴더 제거하는 방법
지난 번에 폴더 자체를 복사하는 것을 하였다. https://data-newbie.tistory.com/266 Linux copy를 할 때 폴더나 파일 덮어써는 방법 폴더 복사를 하려고 하는데, 한번 하고 나니 폴더가 있다면서 복사가 되지 않았다. cp -r from_folder to_folder 이런식으로 진행을 하니 파일이 존재한다해서 안된다고 해서 방법을 찾아보니 다음과 같았다. cp -.. data-newbie.tistory.com 근데 복사를 하다보니 __pycache__ 라는 이상한 폴더도 같이 생기는 것을 확인했다. 원하는 상황은 주어진 것만 없애고 싶기 때문에 또 열심히 검색 검색 답은 요거였다. ## os.system("find {} | grep -E '(__pycache__|\.pyc$..
2019.09.20 -
[ Python ] 새로 만든 함수 수정 후 restart 안하고 reload하기
함수를 잘 못 짜서 다시 load를 해야하는 경우에 함수만 바꾼다고 해서 이미 올라간 것이 바뀌지 않는다. 그래서 위에 2줄을 써주면 다시 load가 되서 수정된 것이 반영된다. %load_ext autoreload %autoreload 2 from custom_package import *
2019.09.18 -
[ Python ] custom logging level 만들기
logging level 추가하기. import logging trace = 15 class user(logging.Logger) : def trace(self , msg , *args ,**kwargs ): self.log( trace ,msg , *args ,**kwargs ) logging.setLoggerClass(user) logging.addLevelName(15 , "user") logger = logging.getLogger("test") logger.setLevel("user") ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(ch) logger.debug(" debug test") logger.trace..
2019.09.11 -
[ Python ] imputation algorithm package 정리
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ categorical 변수 가장 빈도수 많은 것으로 대체할 때, df_most_common_imputed = colors.apply(lambda x: x.fillna(x.value_counts().index[0])) df_most_common_imputed ## scikit-learn 0.2 버전 imputer=CategoricalImputer(strategy='most_frequent', axis=1) imputer.fit(df[["col1", "col2"]]) imputer.transform(df) (https://stackoverflow.com/questions/25239958/impute-categorical-missi..
2019.09.10 -
[ Python ] How to fast String to pandas data frame 연습
Original code 기존에는 1줄 처리하는데 0.1초 그리고 중간에 np.place 에서 문제가 있었음 그리고 타입변환은 현재 숫자로 되어있는것이 object로 되어있기때문에 그 부분만 바꿔주면 되는 문제였음 x = np.array(x.split(",")) np.place(x , x == '' , np.nan) ## warning raw= pd.DataFrane(x.reshpae(1,-1) , columns = col ).astype(type_change) Develop code 0.02초 !!! 5배 향상!! def type_change(x) : try : x = float(x) except : x = x return x x2 = [ ( np.nan if re.match(r"\s" , i) is ..
2019.09.04 -
[ Python ] logging 만들어보기 (FileHandler 와 StreamHandler 위주로)
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ 파이썬에서 logging 쌓기 (FileHandler 와 StreamHandler 위주로) StreamHandler Console에 log 남기기 logging.StreamHandler() FileHandler log를 계속 쌓고 싶을 때 FileHandler('./log.txt' ,mode = "w") RotatingFileHandler 파일 용량을 정해서 log를 쌓고 제거할 때 RotatingFileHandler( filename, ## ~~.log / ~~.txt mode='a', ## a : append / w : overwrite maxBytes=0, ## 한 파일당 몇 몇가 byte까지 만들 수 있는지 backup..
2019.08.25 -
[ Python ] multiprocessing / concurrent.futures
멀티프로세싱 공부 Queues FIFO(선입선출) 먼저 들어온 놈이 먼저 나간다라고 한다. 안에서 쌓아놨다고 내뱉는 머 그런 느낌! 순서가 중요할 때 안전하게 사용해야 하는 느낌이다. from multiprocessing import Process, Queue import random def rand_num(queue , x): #num = random.random() queue.put(x) if __name__ == "__main__": processes = [Process(target=rand_num, args=(queue,x,)) for x in range(10)] for p in processes: p.start() for p in processes: p.join() results = [queue..
2019.08.18