What is jupyter notebook

What is jupyter notebook

What is jupyter notebook

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

JupyterLab: A Next-Generation Notebook Interface

JupyterLab is the latest web-based interactive development environment for notebooks, code, and data. Its flexible interface allows users to configure and arrange workflows in data science, scientific computing, computational journalism, and machine learning. A modular design invites extensions to expand and enrich functionality.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Jupyter Notebook: The Classic Notebook Interface

The Jupyter Notebook is the original web application for creating and sharing computational documents. It offers a simple, streamlined, document-centric experience.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Language of choice

Jupyter supports over 40 programming languages, including Python, R, Julia, and Scala.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Share notebooks

Notebooks can be shared with others using email, Dropbox, GitHub and the Jupyter Notebook Viewer.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Interactive output

Your code can produce rich, interactive output: HTML, images, videos, LaTeX, and custom MIME types.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Big data integration

Leverage big data tools, such as Apache Spark, from Python, R, and Scala. Explore that same data with pandas, scikit-learn, ggplot2, and TensorFlow.

A multi-user version of the notebook designed for companies, classrooms and research labs

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Pluggable authentication

Manage users and authentication with PAM, OAuth or integrate with your own directory service system.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Centralized deployment

Deploy the Jupyter Notebook to thousands of users in your organization on centralized infrastructure on- or off-site.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Container friendly

Use Docker and Kubernetes to scale your deployment, isolate user processes, and simplify software installation.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Code meets data

Deploy the Notebook next to your data to provide unified software management and data access within your organization.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Voilà: Share your results

Voilà helps communicate insights by transforming notebooks into secure, stand-alone web applications that you can customize and share.

Currently in use at

Open Standards for Interactive Computing

Project Jupyter promotes open standards that third-party developers can leverage to build customized applications. Think HTML and CSS for interactive computing on the web.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Notebook Document Format

Jupyter Notebooks are an open document format based on JSON. They contain a complete record of the user’s sessions and include code, narrative text, equations, and rich output.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Interactive Computing Protocol

The Notebook communicates with computational Kernels using the Interactive Computing Protocol, an open network protocol based on JSON data over ZMQ, and WebSockets.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

The Kernel

Kernels are processes that run interactive code in a particular programming language and return output to the user. Kernels also respond to tab completion and introspection requests.

What is the Jupyter Notebook?¶

Introduction¶

These documents provide a complete and self-contained record of a computation that can be converted to various formats and shared with others using email, Dropbox, version control systems (like git/GitHub) or nbviewer.jupyter.org.

Components¶

The Jupyter Notebook combines three components:

Notebook web application¶

The notebook web application enables users to:

Kernels¶

Through Jupyter’s kernel and messaging architecture, the Notebook allows code to be run in a range of different programming languages. For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in the following languages:

The default kernel runs Python code. The notebook provides a simple way for users to pick which of these kernels is used for a given notebook.

Each of these kernels communicate with the notebook web application and web browser using a JSON over ZeroMQ/WebSockets message protocol that is described here. Most users don’t need to know about these details, but it helps to understand that “kernels run code.”

Notebook documents¶

Notebook documents contain the inputs and outputs of an interactive session as well as narrative text that accompanies the code but is not meant for execution. Rich output generated by running code, including HTML, images, video, and plots, is embeddeed in the notebook, which makes it a complete and self-contained record of a computation.

When you run the notebook web application on your computer, notebook documents are just files on your local filesystem with a «.ipynb« extension. This allows you to use familiar workflows for organizing your notebooks into folders and sharing them with others.

Notebooks consist of a linear sequence of cells. There are four basic cell types:

Internally, notebook documents are `JSON `__ data with binary values `base64 `__ encoded. This allows them to be read and manipulated programmatically by any programming language. Because JSON is a text format, notebook documents are version control friendly.

Notebooks can be exported to different static formats including HTML, reStructeredText, LaTeX, PDF, and slide shows (reveal.js) using Jupyter’s nbconvert utility.

Furthermore, any notebook document available from a public URL on or GitHub can be shared via nbviewer. This service loads the notebook document from the URL and renders it as a static web page. The resulting web page may thus be shared with others without their needing to install the Jupyter Notebook.

Особенности Jupyter Notebook, о которых вы (может быть) не слышали

Jupyter Notebook – это крайне удобный инструмент для создания красивых аналитических отчетов, так как он позволяет хранить вместе код, изображения, комментарии, формулы и графики:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Ниже мы расскажем о некоторых фишках, которые делают Jupyter очень крутым. О них можно прочитать и в других местах, но если специально не задаваться этим вопросом, то никогда и не прочитаешь.

Jupyter поддерживает множество языков программирования и может быть легко запущен на любом сервере, необходим только доступ по ssh или http. К тому же это свободное ПО.

Основы

Список хоткеев вы найдете в Help > Keyboard Shortcuts (список периодически дополняется, так что не стесняйтесь заглядывать туда снова).

Отсюда можно получить представление о взаимодействии с блокнотом (notebook). Если вы будете постоянно работать c Jupyter, большинство комбинаций вы быстро выучите.

Экспорт блокнота

Простейший способ — сохранить блокнот в формате IPython Notebook (.ipynb), но так как их используют не все, есть и другие варианты:

Построение графиков

Есть несколько вариантов построения графиков:

Magic-команды

Магические команды (magics) превращают обычный python в магический python. Magic-команды — это ключ к могуществу IPython’а.

Можно управлять переменными среды для вашего блокнота без перезапуска Jupyter-сервера. Некоторые библиотеки (такие, как theano) используют переменные среды, чтобы контролировать поведение, и %env — самый удобный способ.

Выполнение shell-команд

В Notebook можно вызвать любую shell-команду. Это особенно удобно для управления виртуальной средой.

Подавление вывода последней строки

Иногда вывод не нужен, и в этом случае можно или использовать команду pass с новой строки, или поставить точку запятой в конце строки:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

вызовет следующее всплывающее окно:

Используйте %run для выполнения кода на Python

Но эта команда может выполнять и другие блокноты из Jupyter! Иногда это очень полезно.

Обратите внимание, что %run — это не то же, что импорт python-модуля.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Загрузит код напрямую в ячейку. Можно выбрать файл локально или из сети.

Если раскомментировать и выполнить код ниже, содержание ячейки заменится на содержание файла.

%store — ленивая передача данных между блокнотами

%who для анализа переменных глобального пространства имен

Тайминг

Если вы хотите замерить время выполнения программы или найти узкое место в коде, на помощь придет IPython.

Профилирование: %prun, %lprun, %mprun

%lprun позволяет профилировать с точностью до строк кода, но, кажется, в последнем релизе Python он не работает, так что в этот раз обойдемся без магии:

Дебаг с помощью %debug

У Jupyter есть собственный интерфейс для ipdb, что позволяет зайти внутрь функции и посмотреть, что в ней происходит.

Это не PyCharm — потребуется время, чтобы освоить, но при необходимости дебага на сервере это может быть единственным вариантом (кроме pdb через терминал).

Немного более простой способ — команда %pdb, которая активирует дебаггер, когда выбрасывается исключение:

Запись формул в LateX

Маркдаун ячейки могут отрисовывать формулы LateX с помощью MathJax.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Маркдаун — важная часть блокнотов, так что не забывайте использовать его выразительные возможности!

Использование разных языков внутри одного блокнота

Если вы соскучились по другим языкам программирования, можете использовать их в Jupyter Notebook:

Анализ Big Data

Существует несколько решений, чтобы запрашивать/обрабатывать большие объемы данных:

Ваши коллеги могут экспериментировать с вашим кодом, ничего не устанавливая

Такие сервисы, как mybinder, предоставляют доступ к Jupiter Notebook со всеми установленными библиотеками, так что пользователь может с полчаса поиграться с вашим кодом, имея под рукой только браузер.

Вы также можете установить вашу собственную системы с помощью jupyterhub, что очень удобно, если вы проводите мини-курс или мастер-класс и вам некогда думать о машинах для студентов.

Написание функций на других языках

Иногда скорости NumPy бывает недостаточно, и мне необходимо написать немного быстрого кода. В принципе, можно собрать нужные функции в динамические библиотеки, а затем написать обертку на Python…

Но гораздо лучше, когда скучная часть работы сделана за нас, правда?

Ведь можно написать нужные функции на Cython или Fortran и использовать их напрямую из кода на Python.

Для начала нужно установить модули

Лично я предпочитаю Fortran, на котором, я считаю, удобно писать функции для обработки большого объема численных данных. Подробнее о его использовании можно почитать здесь.

Должен заметить, что есть и другие способы ускорить ваш код на Python. Примеры можно найти в моем блокноте.

Множественный курсор

С недавнего времени Jupyter поддерживает множественный курсор, такой, как в Sublime или IntelliJ!

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
Источник: swanintelligence.com/multi-cursor-in-jupyter.html

Расширения Jupyter-contrib

устанавливаются с помощью

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Это целое семейство различных расширений, включая, например, jupyter spell-checker и code-formatter, которых по умолчанию в Jupyter нет.

RISE: презентации в Notebook

Расширение, написанное Damian Avila, позволяет демонстрировать блокноты как презентации. Пример такой презентации: bollwyvl.github.io/live_reveal/#/7

Это может пригодиться, если вы обучаете использованию какой-либо библиотеки.

Система вывода Jupyter

Блокноты отображаются в HTML, и вывод ячейки тоже может быть в формате HTML, так что вы можете выводить все, что душе угодно: видео, аудио, изображения.

В этом примере я просматриваю содержимое директории с картинками в моем репозитории и отображаю первые пять из них.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook
What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Я мог бы получить тот же список bash-командой,

потому что magic-команды и bash-вызовы возвращают переменные Python:

Повторное подключение к ядру

Давным давно, если вы запускали какой-нибудь долгий процесс и в какой-то момент подключение к серверу IPython прерывалось, вы полностью теряли возможность отслеживать процесс вычислений (если только вы не записывали эти данные в файл). Приходилось или прерывать работу ядра с риском потерять некоторые результаты, или ждать окончания процесса, не имея представления о том, что в данный момент происходит.

Теперь опция Reconnect to kernel позволяет заново подключиться к работающему ядру, не прерывая вычислений, и увидеть последний вывод (хотя какая-то часть вывода все же будет потеряна).

Пишите ваши посты в Notebook

такие, как этот. Используйте nbconvert, чтобы экспортировать в HTML.

Jupyter Notebook: An Introduction

Table of Contents

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Jupyter Notebooks

The Jupyter Notebook is an open source web application that you can use to create and share documents that contain live code, equations, visualizations, and text. Jupyter Notebook is maintained by the people at Project Jupyter.

Jupyter Notebooks are a spin-off project from the IPython project, which used to have an IPython Notebook project itself. The name, Jupyter, comes from the core supported programming languages that it supports: Julia, Python, and R. Jupyter ships with the IPython kernel, which allows you to write your programs in Python, but there are currently over 100 other kernels that you can also use.

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Getting Up and Running With Jupyter Notebook

The Jupyter Notebook is not included with Python, so if you want to try it out, you will need to install Jupyter.

There are many distributions of the Python language. This article will focus on just two of them for the purposes of installing Jupyter Notebook. The most popular is CPython, which is the reference version of Python that you can get from their website. It is also assumed that you are using Python 3.

Installation

If so, then you can use a handy tool that comes with Python called pip to install Jupyter Notebook like this:

The next most popular distribution of Python is Anaconda. Anaconda has its own installer tool called conda that you could use for installing a third-party package. However, Anaconda comes with many scientific libraries preinstalled, including the Jupyter Notebook, so you don’t actually need to do anything other than install Anaconda itself.

Starting the Jupyter Notebook Server

Now that you have Jupyter installed, let’s learn how to use it. To get started, all you need to do is open up your terminal application and go to a folder of your choice. I recommend using something like your Documents folder to start out with and create a subfolder there called Notebooks or something else that is easy to remember.

Then just go to that location in your terminal and run the following command:

This will start up Jupyter and your default browser should start (or open a new tab) to the following URL: http://localhost:8888/tree

Your browser should now look something like this:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Note that right now you are not actually running a Notebook, but instead you are just running the Notebook server. Let’s actually create a Notebook now!

Creating a Notebook

Now that you know how to start a Notebook server, you should probably learn how to create an actual Notebook document.

All you need to do is click on the New button (upper right), and it will open up a list of choices. On my machine, I happen to have Python 2 and Python 3 installed, so I can create a Notebook that uses either of these. For simplicity’s sake, let’s choose Python 3.

Your web page should now look like this:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Naming

You will notice that at the top of the page is the word Untitled. This is the title for the page and the name of your Notebook. Since that isn’t a very descriptive name, let’s change it!

Just move your mouse over the word Untitled and click on the text. You should now see an in-browser dialog titled Rename Notebook. Let’s rename this one to Hello Jupyter:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Running Cells

A Notebook’s cell defaults to using code whenever you first create one, and that cell uses the kernel that you chose when you started your Notebook.

In this case, you started yours with Python 3 as your kernel, so that means you can write Python code in your code cells. Since your initial Notebook has only one empty cell in it, the Notebook can’t really do anything.

Thus, to verify that everything is working as it should, you can add some Python code to the cell and try running its contents.

Let’s try adding the following code to that cell:

When I ran the code above, the output looked like this:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

If you have multiple cells in your Notebook, and you run the cells in order, you can share your variables and imports across cells. This makes it easy to separate out your code into logical chunks without needing to reimport libraries or recreate variables or functions in every cell.

When you run a cell, you will notice that there are some square braces next to the word In to the left of the cell. The square braces will auto fill with a number that indicates the order that you ran the cells. For example, if you open a fresh Notebook and run the first cell at the top of the Notebook, the square braces will fill with the number 1.

The Menus

The Jupyter Notebook has several menus that you can use to interact with your Notebook. The menu runs along the top of the Notebook just like menus do in other applications. Here is a list of the current menus:

Let’s go over the menus one by one. This article won’t go into detail for every single option in every menu, but it will focus on the items that are unique to the Notebook application.

The first menu is the File menu. In it, you can create a new Notebook or open a preexisting one. This is also where you would go to rename a Notebook. I think the most interesting menu item is the Save and Checkpoint option. This allows you to create checkpoints that you can roll back to if you need to.

Next is the Edit menu. Here you can cut, copy, and paste cells. This is also where you would go if you wanted to delete, split, or merge a cell. You can reorder cells here too.

Note that some of the items in this menu are greyed out. The reason for this is that they do not apply to the currently selected cell. For example, a code cell cannot have an image inserted into it, but a Markdown cell can. If you see a greyed out menu item, try changing the cell’s type and see if the item becomes available to use.

The View menu is useful for toggling the visibility of the header and toolbar. You can also toggle Line Numbers within cells on or off. This is also where you would go if you want to mess about with the cell’s toolbar.

The Insert menu is just for inserting cells above or below the currently selected cell.

The Cell menu allows you to run one cell, a group of cells, or all the cells. You can also go here to change a cell’s type, although I personally find the toolbar to be more intuitive for that.

The other handy feature in this menu is the ability to clear a cell’s output. If you are planning to share your Notebook with others, you will probably want to clear the output first so that the next person can run the cells themselves.

The Kernel cell is for working with the kernel that is running in the background. Here you can restart the kernel, reconnect to it, shut it down, or even change which kernel your Notebook is using.

You probably won’t be working with the Kernel all that often, but there are times when you are debugging a Notebook that you will find you need to restart the Kernel. When that happens, this is where you would go.

The Widgets menu is for saving and clearing widget state. Widgets are basically JavaScript widgets that you can add to your cells to make dynamic content using Python (or another Kernel).

Finally you have the Help menu, which is where you go to learn about the Notebook’s keyboard shortcuts, a user interface tour, and lots of reference material.

Starting Terminals and Other Things

The Terminal is probably the most interesting of the bunch, as it is running your operating systems terminal in the browser. This allows you to run bash, Powershell, and so on in your browser and run any shell command that you might need to there.

Viewing What’s Running

Also on the home page of your Jupyter server ( http://localhost:8888/tree ) are two other tabs: Running and Clusters.

The Running tab will tell you which Notebooks and Terminals you are currently running. This is useful for when you want to shut down your server but you need to make sure that you have saved all your data. Fortunately, Notebooks auto-save pretty frequently, so you rarely lose data. But it’s good to be able to see what’s running when you need to.

The other nice thing about this tab is that you can go through your running applications and shut them down there.

Adding Rich Content

Jupyter Notebook supports adding rich content to its cells. In this section, you will get an overview of just some of the things you can do with your cells using Markup and Code.

Cell Types

There are technically four cell types: Code, Markdown, Raw NBConvert, and Heading.

The Heading cell type is no longer supported and will display a dialog that says as much. Instead, you are supposed to use Markdown for your Headings.

The Raw NBConvert cell type is only intended for special use cases when using the nbconvert command line tool. Basically it allows you to control the formatting in a very specific way when converting from a Notebook to another format.

The primary cell types that you will use are the Code and Markdown cell types. You have already learned how code cells work, so let’s learn how to style your text with Markdown.

Styling Your Text

Jupyter Notebook supports Markdown, which is a markup language that is a superset of HTML. This tutorial will cover some of the basics of what you can do with Markdown.

Set a new cell to Markdown and then add the following text to the cell:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

When you run the cell, the output should look like this:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

If you would prefer to bold your text, use a double underscore or double asterisk.

Headers

Creating headers in Markdown is also quite simple. You just have to use the humble pound sign. The more pound signs you use, the smaller the header. Jupyter Notebook even kind of previews it for you:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Then when you run the cell, you will end up with a nicely formatted header:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Creating Lists

You can create a list (bullet points) by using dashes, plus signs, or asterisks. Here is an example:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Code and Syntax Highlighting

If you want to insert a code example that you don’t want your end user to actually run, you can use Markdown to insert it. For inline code highlighting, just surround the code with backticks. If you want to insert a block of code, you can use triple backticks and also specify the programming language:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Exporting Notebooks

When you are working with Jupyter Notebooks, you will find that you need to share your results with non-technical people. When that happens, you can use the nbconvert tool which comes with Jupyter Notebook to convert or export your Notebook into one of the following formats:

Jinja is a template engine that was made for Python. Also note that nbconvert also depends on Pandoc and TeX to be able to export to all the formats above. If you don’t have one or more of these, some of the export types may not work. For more information, you should check out the documentation.

How to Use nbconvert

The nbconvert command does not take very many parameters, which makes learning how to use it easier. Open up a terminal and navigate to the folder that contains the Notebook you wish to convert. The basic conversion command looks like this:

Example Usage

Let’s pretend that you have a Notebook named py_examples.ipynb and you want to convert it to PDF. Here is the command you would use to do that:

When you run this command, you should see some output that tells you about the conversion process. nbconvert will display warnings and errors if there are any. Assuming everything goes according to plan, you will now have a py_examples.pdf file in your folder.

The conversion process for the other file types is quite similar. You just have to tell nbconvert what type to convert to (PDF, Markdown, HTML, and so on).

Use the Menu

You can also export your currently running Notebook by going to the File menu and choosing the Download as option.

This option allows you to download in all the formats that nbconvert supports. The benefit of using the menu is that you don’t need to learn the nbconvert at all if you don’t want to. However I recommend doing so as you can use nbconvert to export multiple Notebooks at once, which is something that the menu does not support.

Notebook Extensions

While Jupyter Notebooks have lots of functionality built in, you can add new functionality through extensions. Jupyter actually supports four types of extensions:

This tutorial will focus on Notebook extensions.

What Are Extensions?

A Notebook extension ( nbextension ) is a JavaScript module that you load in most of the views in the Notebook’s frontend. If you are handy with JavaScript, you can even write your own extension. An extension can access the page’s DOM and the Jupyter JavaScript API.

Where Do I Get Extensions?

How Do I Install Them?

This only installs the extension but does not make it active. You will need to enable an extension after installing it by running the following:

You may need to restart your Jupyter Notebook kernel to see the extension.

There is a nice meta extension called Jupyter NbExtensions Configurator that is worth getting for managing other extensions. It allows you to enable and disable your extensions from within the Jupyter Notebook’s user interface and also shows all the currently installed extensions.

Conclusion

The Jupyter Notebook is quite useful not only for learning and teaching a programming language such as Python but also for sharing your data.

You can turn your Notebook into a slideshow or share it online with GitHub. If you want to share a Notebook without requiring your users to install anything, you can use binder for that.

Google and Microsoft both have their own version of the Notebook that you can use to create and share your Notebooks at Google Colaboratory and Microsoft Azure Notebooks respectively. You can browse really interesting Notebooks there as well.

Project Jupyter recently launched their latest product, JupyterLab. JupyterLab incorporates Jupyter Notebook into an Integrated Development type Editor that you run in your browser. You can kind of think of JupyterLab as an advanced version of Jupyter Notebook. JupyterLab allows you to run terminals, text editors and code consoles in your browser in addition to Notebooks.

As always, it is best to try out a new piece of software yourself to see if it suits you and is worth using. I encourage you to give Jupyter Notebook or JupyterLab a spin and see what you think!

Further Reading

If you want to learn more about Jupyter Notebook, you can take a moment and read their excellent documentation.

For more information on Integrated Development Environments, you might want to check out the following articles:

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Jupyter Notebooks

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

About Mike Driscoll

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Mike has been programming in Python for over a decade and loves writing about Python!

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Master Real-World Python Skills With Unlimited Access to Real Python

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Related Tutorial Categories: intermediate tools

The Jupyter Notebook¶

Introduction¶

The notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results. The Jupyter notebook combines two components:

A web application: a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output.

Notebook documents: a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects.

See the installation guide on how to install the notebook and its dependencies.

Main features of the web application¶

Notebook documents¶

Notebooks may be exported to a range of static formats, including HTML (for example, for blog posts), reStructuredText, LaTeX, PDF, and slide shows, via the nbconvert command.

Starting the notebook server¶

You can start running a notebook server from the command line using the following command:

This will print some information about the notebook server in your console, and open a web browser to the URL of the web application (by default, http://127.0.0.1:8888 ).

The landing page of the Jupyter notebook web application, the dashboard, shows the notebooks currently available in the notebook directory (by default, the directory from which the notebook server was started).

When you are inside an open notebook, the File | Open… menu option will open the dashboard in a new browser tab, to allow you to open another notebook from the notebook directory or to create a new notebook.

Creating a new notebook document¶

A new notebook may be created at any time, either from the dashboard, or using the File ‣ New menu option from within an active notebook. The new notebook is created within the same directory and will open in a new browser tab. It will also be reflected as a new entry in the notebook list on the dashboard.

What is jupyter notebook. Смотреть фото What is jupyter notebook. Смотреть картинку What is jupyter notebook. Картинка про What is jupyter notebook. Фото What is jupyter notebook

Opening notebooks¶

An open notebook has exactly one interactive session connected to a kernel, which will execute code sent by the user and communicate back results. This kernel remains active if the web browser window is closed, and reopening the same notebook from the dashboard will reconnect the web application to the same kernel. In the dashboard, notebooks with an active kernel have a Shutdown button next to them, whereas notebooks without an active kernel have a Delete button in its place.

Other clients may connect to the same kernel. When each kernel is started, the notebook server prints to the terminal a message like this:

You can then, for example, manually start a Qt console connected to the same kernel from the command line, by passing a portion of the ID:

With the IPython kernel, you can also run the %qtconsole magic in the notebook to open a Qt console connected to the same kernel.

Notebook user interface¶

When you create a new notebook document, you will be presented with the notebook name, a menu bar, a toolbar and an empty code cell.

menu bar: The menu bar presents different options that may be used to manipulate the way the notebook functions.

toolbar: The tool bar gives a quick way of performing the most-used operations within the notebook, by clicking on an icon.

code cell: the default type of cell, read on for an explanation of cells

Structure of a notebook document¶

For more information on the different things you can do in a notebook, see the collection of examples.

Code cells¶

When a code cell is executed, code that it contains is sent to the kernel associated with the notebook. The results that are returned from this computation are then displayed in the notebook as the cell’s output. The output is not limited to text, with many other possible forms of output are also possible, including matplotlib figures and HTML tables (as used, for example, in the pandas data analysis package). This is known as IPython’s rich display capability.

Markdown cells¶

You can document the computational process in a literate way, alternating descriptive text with code, using rich text. In IPython this is accomplished by marking up text with the Markdown language. The corresponding cells are called Markdown cells. The Markdown language provides a simple way to perform this text markup, that is, to specify which parts of the text should be emphasized (italics), bold, form lists, etc.

When a Markdown cell is executed, the Markdown code is converted into the corresponding formatted rich text. Markdown allows arbitrary HTML code for formatting.

Raw cells¶

Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

Heading cells¶

If you want to provide structure for your document, you can use markdown headings. Markdown headings consist of 1 to 6 hash # signs # followed by a space and the title of your section. The markdown heading will be converted to a clickable link for a section of the notebook. It is also used as a hint when exporting to other document formats, like PDF. We recommend using only one markdown header in a cell and limit the cell’s content to the header text. For flexibility of text format conversion, we suggest placing additional text in the next notebook cell.

Basic workflow¶

The normal workflow in a notebook is, then, quite similar to a standard IPython session, with the difference that you can edit cells in-place multiple times until you obtain the desired results, rather than having to rerun separate scripts with the %run magic command.

Typically, you will work on a computational problem in pieces, organizing related ideas into cells and moving forward once previous parts work correctly. This is much more convenient for interactive exploration than breaking up a computation into scripts that must be executed together, as was previously necessary, especially if parts of them take a long time to run.

Keyboard shortcuts¶

All actions in the notebook can be performed with the mouse, but keyboard shortcuts are also available for the most common ones. The essential shortcuts to remember are the following:

Plotting¶

One major feature of the Jupyter notebook is the ability to display plots that are the output of running code cells. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality. Specific plotting library integration is a feature of the kernel.

Installing kernels¶

For information on how to install a Python kernel, refer to the IPython install page.

Kernels for other languages can be found in the IPython wiki. They usually come with instruction what to run to make the kernel available in the notebook.

Signing Notebooks¶

To prevent untrusted code from executing on users’ behalf when notebooks open, we have added a signature to the notebook, stored in metadata. The notebook server verifies this signature when a notebook is opened. If the signature stored in the notebook metadata does not match, javascript and HTML output will not be displayed on load, and must be regenerated by re-executing the cells.

Any notebook that you have executed yourself in its entirety will be considered trusted, and its HTML and javascript output will be displayed on load.

If you need to see HTML or Javascript output without re-executing, you can explicitly trust notebooks, such as those shared with you, or those that you have written yourself prior to IPython 2.0, at the command-line with:

This just generates a new signature stored in each notebook.

You can generate a new notebook signing key with:

Browser Compatibility¶

The Jupyter Notebook is officially supported by the latest stable versions of the following browsers:

The is mainly due to the notebook’s usage of WebSockets and the flexible box model.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *