[jupyter] Practical tips for jupyter under mac os system

Insert image description here

Jupyter notebook is an open source web application that allows you to create and share documents containing code, formulas, visualizations and narrative text. It can be used for data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning and other purposes.

There are many ways to install jupyter notebook under mac os system. Here are two commonly used methods:

Method 1: Use pip to install jupyter notebook

pip is Python's package management tool, which can easily install and uninstall Python's third-party libraries. The steps to install jupyter notebook using pip are as follows:

  1. Install the latest version of Python3 and enter python3 --version in the terminal to check whether the installation is successful.
  2. Check whether pip3 is installed correctly. Enter pip3 --version in the terminal to view the version information.
  3. To upgrade pip3 to avoid errors during installation, enter pip3 install --upgrade pip in the terminal to execute the upgrade command.
  4. Use pip3 to install jupyter notebook, and enter pip3 install jupyter in the terminal to execute the installation command.

Method 2: Use setup.py to install jupyter notebook

setup.py is a packaging tool for Python that can compile and install Python third-party libraries from source code. The steps to install jupyter notebook using setup.py are as follows:

  1. Download the latest source code package of jupyter notebook, which can be found here , or you can enter curl https://files.pythonhosted.org/packages/c9/a9/371d0b8fe37dd231cf4b2cff0a9f0f25e98f3a73c3771742444be27f2944/jupyter-1.0.0.tar.gz > jupyter. tar.gz is downloaded to the current directory.
  2. Decompress the downloaded source code package and enter tar -xzvf jupyter.tar.gz in the terminal to execute the decompression command.
  3. Enter the decompressed folder and enter cd jupyter-1.0.0 in the terminal to switch to the source directory.
  4. Use setup.py to install jupyter notebook, and enter python3 setup.py install in the terminal to execute the installation command. Note: You must have the XCode MacOS developer tools installed on your system.

Verify jupyter notebook installation

No matter which method is used to install jupyter notebook, you can enter jupyter notebook in the terminal to start jupyter notebook and verify whether the installation is successful. If no errors occur, the installation is successful.

In addition to installing jupyter notebook, there are also some practical tips that can help you use jupyter notebook more efficiently. Here are some common techniques, including but not limited to indentation, comments, etc., and give specific examples.

keyboard shortcuts

Keyboard shortcuts can save you a lot of time and let you operate Jupyter notebook faster. Jupyter notebook provides many keyboard shortcuts, which you can find in the menu bar: Help > Keyboard Shortcuts, or press H in command mode (described later) to view them. It's worth checking the keyboard shortcuts every time you update your Jupyter notebook, as some new ones may be added.

Command mode and edit mode

Jupyter notebook has two modes: command mode and editing mode. In command mode, you can use keyboard shortcuts to operate cells, such as insert, delete, move, copy, paste, etc. In edit mode, you can enter code or text into cells. You can tell which mode is currently in by the color on the left side of the cell: blue indicates command mode and green indicates edit mode.

You can use the Esc key to switch from edit mode to command mode and the Enter key to switch from command mode to edit mode. In command mode, you can also double-click the mouse or press the B key to create a new cell.

cell type

Jupyter notebook supports two types of cells: code cells and Markdown cells. Code cells allow you to enter and execute Python code, and Markdown cells allow you to enter and render Markdown text. Markdown is a lightweight markup language that allows you to format text with simple symbols, such as bold, italics, titles, lists, links, etc.

You can use the M key in command mode to convert the current cell to a Markdown cell, and the Y key to convert the current cell to a code cell. You can also select Cell > Cell Type in the menu bar to switch cell types.

execute cell

To execute a cell of code, you can press Shift + Enter, which will execute the current cell and jump to the next cell. If the next cell does not exist, a new code cell is created. You can also press Ctrl + Enter, which will execute the current cell and keep it at the current location. If you want to execute the current cell and insert a new code cell below, you can press Alt + Enter.

To execute a Markdown cell, you can also press Shift + Enter or Ctrl + Enter, which will render the current cell's text and jump to the next cell or stay at the current position. If you want to edit a rendered Markdown cell again, you can double-click it or press Enter to enter edit mode.

Indentation and comments

Indentation and comments are important when writing Python code. Indentation can make your code clearer and more standardized, and comments can make your code more understandable and maintainable. Jupyter Notebook provides some shortcut keys to help you with indentation and comments.

To indent one or more lines of code, you can select them and press the Tab key, which will add four spaces at the beginning of each line. To unindent one or more lines of code, you can select them and press Shift + Tab, which will remove the four spaces at the beginning of each line.

To comment out one or more lines of code, you can select them and press Cmd + / (or Ctrl + / on Linux and Windows), which will add a # symbol at the beginning of each line. To uncomment one or more lines of code, you can also select them and press Cmd + / (or Ctrl + / on Linux and Windows), which will remove the # symbol at the beginning of each line.

magic command

Jupyter notebook supports some special commands, called magic commands, which start with % or %%, which allow you to perform some additional functions in cells, such as timing, running code in other languages, displaying charts, etc. There are two types of magic commands: line magic and cell magic. Row magic starts with % and is only effective for the current row. Cell magic starts with %% and is effective for the entire cell.

You can select Help > Magic in the menu bar to see a list of all available magic commands. Here are some examples of magic commands:

  • %timeit: This line magic can measure the execution time of a single statement, such as a list comprehension or a function call. For example:
%timeit [x**2 for x in range(1000)]

This will output something like:

1000 loops, best of 5: 248 µs per loop
  • %%timeit: This cell magic can measure the execution time of the whole cell, such as a for loop or a code block. For example:
%%timeit
sum = 0
for i in range(1000):
    sum += i**2

This will output something like:

1000 loops, best of 5: 331 µs per loop
  • %matplotlib: This line magic can enable the inline display of matplotlib plots in the notebook. You can also specify a different backend, such as qt or tk, to show the plots in a separate window. For example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

This will output a plot like this:

  • %%writefile: This cell magic can write the content of the cell to a file. You need to specify the file name as an argument. For example:
%%writefile hello.py
print("Hello, world!")

This will create a file named hello.py with the content print(“Hello, world!”).

  • %run: This line magic can execute a Python script and load its content to the current namespace. You need to specify the script name as an argument. For example:
%run hello.py

This will execute the hello.py script and output Hello, world!.

  • %%bash: This cell magic can run a bash script in the cell. You can use any bash commands in the cell. For example:
%%bash
echo "Current date and time:"
date
echo "Current directory:"
pwd
echo "Current user:"
whoami

This will output something like:

Current date and time:
Sat May  6 10:29:03 CST 2023
Current directory:
/Users/user/Desktop/jupyter-notebook-tips
Current user:
user

Interactive widgets

Jupyter notebook supports some interactive widgets, which allow you to create some visual controls in cells, such as sliders, buttons, check boxes, etc. These controls can interact with Python code to achieve some dynamic effects. To use interactive widgets, you need to import the ipywidgets module and use the interact or interactive functions to create the control. For example:

from ipywidgets import interact
import numpy as np
import matplotlib.pyplot as plt

def f(n):
    x = np.linspace(0, 10, 100)
    y = np.sin(n * x)
    plt.plot(x, y)
    plt.show()

interact(f, n=(1, 10))

This creates a slider that lets you adjust the value of n, thereby changing the frequency of the sinusoid.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-OQze2Zd8-1683350343137) (null)]

LaTeX official

jupyter notebook supports using LaTeX syntax to input and render mathematical formulas. LaTeX is a professional typesetting system that allows you to represent complex mathematical expressions using simple symbols. To use LaTeX formulas in jupyter notebook, you need to surround the formula with two dollar signs $. For example:

This is a quadratic equation:

a x 2 + b x + c = 0 ax^2 + bx + c = 0 ax2+bx+c=0

This is a matrix:

[ a b c d ] \begin{bmatrix} a & b \\ c & d \end{bmatrix} [acbd]

This is a point:

∫ a b f ( x ) d x \int_{a}^{b} f(x) dx abf(x)dx

This will render to:

This is a quadratic equation:

a x 2 + b x + c = 0 ax^2 + bx + c = 0ax2+bx+c=0

This is a matrix:

[ a b c d ] \begin{bmatrix} a & b \\ c & d \end{bmatrix}[acbd]

This is a point:

∫ a b f ( x ) d x \int_{a}^{b} f(x) dxabf(x)dx

function association

When writing Python code, sometimes you may not remember the name or parameters of a certain function, or you may want to check the documentation for a certain function. Jupyter notebook provides some shortcut keys to help you perform function association.

  • Tab key: When you type the name of a variable or function, you can press the Tab key to automatically complete or display alternative names. For example, when you type plt. and press the Tab key, all functions and properties in the matplotlib.pyplot module will be displayed. When you enter plt.p and press the Tab key, all functions and properties starting with p will be displayed, such as plt.plot, plt.pie, etc. You can use the up and down arrows to select the name you want, then press Enter or Tab to complete it.

  • Shift + Tab: When you type parentheses for a function, you can press Shift + Tab to display the function's signature or documentation. For example, when you type plt.plot( and then press Shift + Tab, the parameters and a brief description of the plt.plot function will be displayed. If you press Shift + Tab again, more detailed documentation will be displayed. If you hold Hold the Shift key and press the Tab key four times in succession to display the complete document in a separate window.

  • ? symbol: When you want to see the details of a variable or function, you can add a question mark? after it and then execute the cell. This displays the variable or function's type, value, documentation, and more in a separate window. For example, when you execute plt.plot?, complete documentation for the plt.plot function is displayed. If you want to close this window, you can press the Esc key or click the x button in the upper right corner of the window.

Guess you like

Origin blog.csdn.net/weixin_50409347/article/details/130524922