Jupyter Notebook 기본 사용법

2024. 7. 30. 15:22개발/개발도구와 환경

1. Jupyter Notebook 시작

# Jupyter Notebook 설치
pip install notebook

# Jupyter Notebook 시작
jupyter notebook

https://jupyter.org/install

 

Project Jupyter

The Jupyter Notebook is a web-based interactive computing platform. The notebook combines live code, equations, narrative text, visualizations, interactive dashboards and other media.

jupyter.org

 

2. 셀 종류

  • Code Cell: 파이썬 코드 작성 및 실행
  • Markdown Cell: 텍스트 서식 지정 (Markdown 문법 사용 - https://gangdonggil.tistory.com/2)
  • Raw Cell: 서식 없이 텍스트 입력

https://jupyter-notebook.readthedocs.io/en/stable/notebook.html#structure-of-a-notebook-document

 

3. 기본 단축키

  • Command Mode (명령 모드): 셀 선택 시
    • Enter: 편집 모드로 전환
    • A: 위에 셀 추가
    • B: 아래에 셀 추가
    • C: 셀 복사
    • V: 셀 붙여넣기
    • D, D: 셀 삭제
    • Z: 셀 실행 취소
    • Y: 코드 셀로 변경
    • M: 마크다운 셀로 변경
    • Shift + Enter: 셀 실행 후 다음 셀로 이동
    • Ctrl + Enter: 셀 실행 후 해당 셀에 머무름

https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Keyboard-Navigation

 

4. 마크다운 사용법 - https://gangdonggil.tistory.com/2

# 제목 (Heading 1)
## 부제목 (Heading 2)
### 소제목 (Heading 3)

**굵은 글씨** (Bold)
*기울임 글씨* (Italic)
- 리스트 항목 1
- 리스트 항목 2

[링크 텍스트](https://example.com)

`코드 인라인` (Inline Code)

https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html

 

5. 코드 실행 및 출력

# 기본적인 파이썬 코드 실행
a = 5
b = 10
print(a + b)

이 코드를 실행해 보자.

 

6. 매직 명령어 (Magic Commands)

  • 라인 매직 (Line Magic): 한 줄의 코드에 적용
    • %time: 코드 실행 시간 측정
    • %matplotlib inline: 그래프를 인라인으로 표시
    • %ls: 현재 디렉토리의 파일 목록 표시
  • 셀 매직 (Cell Magic): 여러 줄의 코드에 적용
    • %%time: 셀 전체의 코드 실행 시간 측정
    • %%writefile: 셀 내용을 파일로 저장

https://ipython.readthedocs.io/en/stable/interactive/magics.html

 

7. 그래프 그리기 코드 예시 (Matplotlib 예시)

import matplotlib.pyplot as plt
import numpy as np

# 데이터 생성
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 그래프 그리기
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

 

 

8. 데이터프레임 표시 코드 예시 (Pandas 예시)

import pandas as pd

# 데이터프레임 생성
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'San Francisco', 'Los Angeles']
}

df = pd.DataFrame(data)

# 데이터프레임 표시
df

 

9. IPython 디스플레이 기능 코드 예시

from IPython.display import display, HTML, Image

# HTML 표시
display(HTML('<h1>Hello, Jupyter!</h1>'))

# 이미지 표시
display(Image(url='https://example.com/image.png'))

 

10. Jupyter Notebook 확장 (nbextensions)

# nbextensions 설치
pip install jupyter_contrib_nbextensions

# nbextensions 적용
jupyter contrib nbextension install --user

# Jupyter Notebook 시작 후, Nbextensions 탭에서 확장 기능 활성화

https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html