Diary of Chanjun 데이터 분석가의 다이어리

데이터 분석가가 Python에서 한번씩 보지만 궁금하지 않았던 것들

학습목적

데이터 분석가로써 가끔 한번씩 혹은 미쳐 몰랐던 파이썬의 기능들의 몇가지를 소개하고, 이해해보도록 한다.


F string


  1. 가장 간단한 방식의 string + string 으로 표현합니다.
    • string의 + 와 int, float의 + 의 연산이 다르기 때문에 숫자를 str()로 다시 감싸주어야 사용할 수 있습니다.
import os
import sys
for i in range(101) :
    if i % 10 == 0 :
        print(str(i) + "번째 for문")
0번째 for문
10번째 for문
20번째 for문
30번째 for문
40번째 for문
50번째 for문
60번째 for문
70번째 for문
80번째 for문
90번째 for문
100번째 for문
  1. 조금 생소해보일 수도 있는 f string입니다.
    • 간단한 작업을 할 때는 효율적이지만 복잡하거나 길어지면 가독성이나 코드가 간단하지는 않습니다.
for i in range(101) :
    if i % 10 == 0 :
        print(f"{i}번째 for문")
0번째 for문
10번째 for문
20번째 for문
30번째 for문
40번째 for문
50번째 for문
60번째 for문
70번째 for문
80번째 for문
90번째 for문
100번째 for문
  1. 아마 가장 자주보는 방식의 string.format() 입니다.
    • 간단해 보이지만 응용할 수 있는 방법들이 다양하게 있습니다.
for i in range(101) :
    if i % 10 == 0 :
        print("{}번째 for문".format(i))
0번째 for문
10번째 for문
20번째 for문
30번째 for문
40번째 for문
50번째 for문
60번째 for문
70번째 for문
80번째 for문
90번째 for문
100번째 for문
print("첫번째 값 : {} \n두번째 값 : {} \n세번째 값 : {}".format(0, 1, 2))
첫번째 값 : 0 
두번째 값 : 1 
세번째 값 : 2
print("첫번째 값 : {} \n두번째 값 : {} \n세번째 값 : {}".format(*[i for i in range(3)]))
첫번째 값 : 0 
두번째 값 : 1 
세번째 값 : 2
print("첫번째 값 : {first_value} \n두번째 값 : {second_value} \n첫번째 값 AGAIN: {first_value} \n두번째 값 AGAIN : {second_value}".format(first_value = 1, second_value = 2))
첫번째 값 : 1 
두번째 값 : 2 
첫번째 값 AGAIN: 1 
두번째 값 AGAIN : 2
print("첫번째 값 : {first_value} \n두번째 값 : {second_value} \n첫번째 값 AGAIN: {first_value} \n두번째 값 AGAIN : {second_value}".format(**{"first_value" : 1, "second_value" : 2}))
첫번째 값 : 1 
두번째 값 : 2 
첫번째 값 AGAIN: 1 
두번째 값 AGAIN : 2





Decorator


def sigma_fromA_toB(A, B) :
    print("result : {}".format(sum(range(A, B + 1))))
sigma_fromA_toB(1,2)
result : 3
import time
stime = time.time()
sigma_fromA_toB(100000,1000000)
etime = time.time()
print("duringtime : {:.4f}".format(etime - stime))
result : 495000550000
duringtime : 0.0177
def sigma_fromA_toB_toTime(A, B) :
    stime = time.time()
    print("result : {}".format(sum(range(A, B + 1))))
    etime = time.time()
    print("duringtime : {:.4f}".format(etime - stime))
sigma_fromA_toB_toTime(100000,1000000)
result : 495000550000
duringtime : 0.0363
def measure_time(func) :
    def measure_time(*args, **kwargs) :
        stime = time.time()
        func(*args, **kwargs)
        etime = time.time()

        print("duringtime : {:.4f}".format(etime - stime))
    return measure_time
@measure_time
def sigma_fromA_toB(A, B) :
    print("result : {}".format(sum(range(A, B + 1))))
sigma_fromA_toB(100000,1000000)
result : 495000550000
duringtime : 0.0204





Under bar/ Under score


언더바 하나만 사용되는 경우 1

for _ in range(10) :
    sigma_fromA_toB(100000,1000000)
result : 495000550000
duringtime : 0.0349
result : 495000550000
duringtime : 0.0222
result : 495000550000
duringtime : 0.0193
result : 495000550000
duringtime : 0.0630
result : 495000550000
duringtime : 0.0373
result : 495000550000
duringtime : 0.0484
result : 495000550000
duringtime : 0.0551
result : 495000550000
duringtime : 0.0290
result : 495000550000
duringtime : 0.0163
result : 495000550000
duringtime : 0.0154
for _ in range(10) :
    sigma_fromA_toB(100000,1000000)
    print(f"_ size is {sys.getsizeof(_)}")
result : 495000550000
duringtime : 0.0177
_ size is 24
result : 495000550000
duringtime : 0.0207
_ size is 28
result : 495000550000
duringtime : 0.0269
_ size is 28
result : 495000550000
duringtime : 0.0599
_ size is 28
result : 495000550000
duringtime : 0.0328
_ size is 28
result : 495000550000
duringtime : 0.0959
_ size is 28
result : 495000550000
duringtime : 0.0295
_ size is 28
result : 495000550000
duringtime : 0.0324
_ size is 28
result : 495000550000
duringtime : 0.0161
_ size is 28
result : 495000550000
duringtime : 0.0151
_ size is 28

언더바 하나만 사용되는 경우 2

a = 1 + 1
a
2
_
2
b = 2 + 2
b
4
_
4
c = 3 + 3
_
4



언더바 위치와 개수에 따른 의미

출처: https://eine.tistory.com/entry/파이썬에서-언더바언더스코어-의-의미와-역할 [아인스트라세의 SW 블로그]





Asterisk(*표)


1. list 앞에 *이 하나만 쓰일 때 : 기본적으로 리스트를 풀 때? 사용된다고 이해하시면 됩니다. 하지만 개별적으로 사용은 안됩니다.

tmp1 = [1,2,3]
tmp2 = [4,5,6]
[tmp1]
[[1, 2, 3]]
[*tmp1]
[1, 2, 3]
[tmp1, tmp2]
[[1, 2, 3], [4, 5, 6]]
[*tmp1, *tmp2]
[1, 2, 3, 4, 5, 6]
*tmp
  File "<ipython-input-53-ca40ad2e4bf3>", line 1
    *tmp
    ^
SyntaxError: can't use starred expression here


2. dict 앞에 *이 하나만 쓰일 때 : dict를 list와 같이 풀 때는 *를 두개 사용해주어야됩니다.

tmp1 = {"a" : 1, "b" : 2, "c" : 3}
tmp2 = {"d" : 4, "e" : 5, "f" : 6}
{**tmp1}
{'a': 1, 'b': 2, 'c': 3}
[tmp1]
[{'a': 1, 'b': 2, 'c': 3}]
[*tmp1]
['a', 'b', 'c']
[**tmp1]
  File "<ipython-input-66-03dc013b6245>", line 1
    [**tmp1]
     ^
SyntaxError: invalid syntax
{**tmp1, **tmp2}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
[*tmp1, *tmp2]
['a', 'b', 'c', 'd', 'e', 'f']
[**tmp1, **tmp2]
  File "<ipython-input-67-7655ba57a350>", line 1
    [**tmp1, **tmp2]
     ^
SyntaxError: invalid syntax


3. 위의 특징을 활용하여 함수에 적용하기

def test_func(a = None, b = None, c = None) :
    print(f"a = {a}, b = {b}, c = {c}")
test_func(1,2,3)
a = 1, b = 2, c = 3
tmp = [[1, 2, 3], [4,5,6], ["ㄱ", "ㄴ", "ㄷ"]]
for t in tmp :
    test_func(t[0], t[1], t[2])
a = 1, b = 2, c = 3
a = 4, b = 5, c = 6
a = ㄱ, b = ㄴ, c = ㄷ
for t in tmp :
    test_func(*t)
a = 1, b = 2, c = 3
a = 4, b = 5, c = 6
a = ㄱ, b = ㄴ, c = ㄷ
def test_func(lr = 0.001, epoch = 100, batch_size = 64) :
    print(f"lr = {lr}, epoch = {epoch}, batch_size = {batch_size}")
tmp1 = {"lr" : 0.000001, "epoch" : 200}
tmp2 = {"epoch" : 200, "batch_size" : 32}
tmp3 = {"epoch" : 200, "lr" : 0.000001, "batch_size" : 128}
tmp = [tmp1, tmp2, tmp3]
for t in tmp :
    test_func(**t)
lr = 1e-06, epoch = 200, batch_size = 64
lr = 0.001, epoch = 200, batch_size = 32
lr = 1e-06, epoch = 200, batch_size = 128





Jupyter Magic key

%lsmagic
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.
%time time.sleep(5)
CPU times: user 706 µs, sys: 1.65 ms, total: 2.36 ms
Wall time: 5 s
%time
time.sleep(3)
time.sleep(2)
CPU times: user 3 µs, sys: 1 µs, total: 4 µs
Wall time: 5.72 µs
%%time 
time.sleep(2)
time.sleep(3)
CPU times: user 948 µs, sys: 1.53 ms, total: 2.48 ms
Wall time: 5 s

code : https://github.com/Chanjun-kim/Chanjun-kim.github.io/blob/main/_ipynb/2021-08-08-PythonTip.ipynb

감사합니다.