노트북에서 사용할 함수 시작할때 자동으로 로드하기

  • 자주 사용하는 라이브러리가 있다면, notebook을 실행할때 자동으로 import 되도록 설정이 가능하다. 예를들어서 pandas의 dataframe의 사이즈를 조정하거나, 자주 사용하는 함수가 있다면 번거롭게 노트마다 등록하지 말고, 하나의 파일로 생성해놓자.

  • ~/.ipython profile_default/에 들어간다.

  • startup의 디렉토리를 생성한다 (아마 있을것이다.)

  • start.py의 파이썬 파일을 생성한다.

  • 파일에 내가 추가할 함수 모듈을 추가한다.

  • 자동으로 notebook에서 import 하는지 확인한다.

startup

startup 디렉토리를 들어가면 README로 친절하게 설명이 되어 있다. 위에의 경우에 start.py로 생성하면 하나의 파일을 생성하기에는 쉽겠지만, 여러개의 단계를 생성하고, 단계를 추가/삭제 하기 위해서는 아래와 같이 순서를 적어주면 알아서 순서대로 수행을 해준다.

This is the IPython startup directory

.py and .ipy files in this directory will be run *prior* to any code or files specified
via the exec_lines or exec_files configurables whenever you load this profile.

Files will be run in lexicographical order, so you can control the execution order of files
with a prefix, e.g.::

    00-first.py
    50-middle.py
    99-last.ipy

start.py


import pandas as pd
import numpy as np

# Pandas options
pd.options.display.max_columns = 30
pd.options.display.max_rows = 20

from IPython import get_ipython
ipython = get_ipython()

# If in ipython, load autoreload extension
if 'ipython' in globals():
    print('\nWelcome to IPython!')
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')

# Display all cell outputs in notebook
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'

# Visualization
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode
init_notebook_mode(connected=True)
import cufflinks as cf
cf.go_offline(connected=True)
cf.set_config_file(theme='pearl')

print('Your favorite libraries have been loaded.')

Autoreload

%load_ext autoreload
%autoreload 2
  • 2의 경우 모든 모듈에서 변화가 있을경우 자동으로 다시 패키지 로드

+ Recent posts