Перейти к содержимому

Как установить jupiter в pycharm

  • автор:

Программирование на Python

Это страница обязательного курса «Программирование на Python», читаемого на программе «Бизнес-информатика» 2 курса бакалавриата в 4 модуле 2022-2023 учебного года.

Занятия ведёт: Тамбовцева Алла Андреевна.

  • 1 Правила игры
  • 2 Программное обеспечение
  • 3 Материалы занятий
    • 3.1 Введение в Python. Переменные и типы данных. Ввод и вывод. (8 апреля)
    • 3.2 Списки и кортежи. Цикл for. Строки и методы на строках. (15 апреля)
    • 3.3 Условные конструкции и цикл while. Работа с текстовыми файлами. (22 апреля)
    • 3.4 Множества и словари (29 апреля)
    • 3.5 Введение в парсинг с BeautifulSoup (13 мая)
    • 3.6 Функции в Python. Lambda-функции (20 мая)
    • 3.7 Массивы NumPy и датафреймы Pandas (27 мая)
    • 3.8 Более продвинутые примеры парсинга и работа с API на примере ВКонтакте (3 июня)
    • 3.9 Более продвинутые примеры парсинга и библиотека Selenium (10 июня)
    • 3.10 Классы в Python. Веб-приложения со streamlit. (17 июня)

    Правила игры

    Формула оценки: Итог = 0.3 * Контрольная работа + 0.3 * Домашние задания + 0.4 * Экзамен.

    • Контрольная работа состоит из двух частей: теоретической и практической. Теоретическая часть содержит тестовые и открытые вопросы по синтаксису, типам и структурам данных в Python, во время её выполнения нельзя запускать код на компьютере и пользоваться материалами. Практическая часть состоит из задач по программированию, во время её выполнения можно пользоваться любыми открытыми источниками, но нельзя создавать новые вопросы на форумах и подобных ресурсах. Оценка за КР – целое число в 10-балльной шкале.
    • Экзамен проходит в том же формате, что и контрольная работа. Оценка за экзамен – целое число в 10-балльной шкале.
    • Домашние задания представляют собой набор задач по программированию по пройденным темам. Оценка за домашние задания – неокруглённое среднее арифметическое за все домашние задания по курсу.

    При сдаче домашнего задания позже указанного срока предусмотрены штрафы. Опоздание в пределах часа ведёт к штрафу 10% от полученной оценки, в пределах суток – к штрафу 30%, в пределах недели – к штрафу 70%.

    Программное обеспечение

    На курсе мы будем работать в двух средах: Jupyter Notebook и PyCharm. Jupyter Notebook мы будем активно использовать в начале курса, плюс, эта среда будет нужна для сдачи домашних заданий через систему с автоматическими тестами для проверки.

    Jupyter Notebook – продукт проекта Jupyter, более простая среда для знакомства с языком, часто используется в дата-аналитике и машинном обучении, позволяет создавать красиво оформленные файлы с кодом, текстом и графиками (файлы с расширением .ipynb).

    Jupyter Notebook можно скачать как отдельно, так и внутри дистрибутива Anaconda, который включает в себя интерпретатор языка Python, библиотеки для обработки, анализа и визуализации данных:

    • Если у вас установлен интерпретатор Python и вы знакомы с командой pip install, можно поставить Jupyter Notebook отдельно по этой инструкции.
    • Если вы не знакомы с Python, рекомендуется поставить дистрибутив Anaconda, скачать можно здесь.

    Также есть возможность работать в Jupyter Notebook онлайн, используя ресурс Google Colab (для создания и редактирования файлов нужен аккаунт Gmail).

    PyCharm – профессиональная среда для разработки, работает преимущественно с исполняемыми файлами, содержащими программы на Python (файлы с расширением .py). PyCharm в бесплатной версии Community умеет открывать ipynb-файлы, созданные в Jupyter Notebook, но только режиме чтения, редактировать их нельзя. Скачать можно здесь, достаточно версии Community.

    Материалы занятий

    Введение в Python. Переменные и типы данных. Ввод и вывод. (8 апреля)

    • Видеозаписи занятий и ipynb-файлы.
    • Знакомство со средой Jupyter Notebook: инструкция по работе, Jupyter Notebook и Markdown (читать, ipynb).
    • Вычисления и переменные в Python (читать, ipynb). Типы данных, ввод и вывод, форматирование строк (читать, ipynb).
    • Практикум 1 (читать, ipynb), решения (читать, ipynb).
    • Стандарты оформления кода Python: PEP8.
    • Pythontutor: визуализатор кода, вычисления, ввод и вывод.
    • Markdown и Jupyter: больше про Markdown, интерактивные виджеты в Jupyter.
    • LaTeX: ShareLaTeX для желающих, документация на английском, материалы других курсов по LaTeX.

    Списки и кортежи. Цикл for. Строки и методы на строках. (15 апреля)

    • Видеозаписи занятий и ipynb-файлы.
    • Списки и цикл for, функция range() (читать, ipynb). Методы на списках (читать, ipynb). Функция zip() и кортежи (читать, ipynb).
    • Строки и методы на строках (читать, ipynb).
    • Практикум 2 (читать, ipynb), решения (читать, ipynb).
    • Pythontutor: списки, цикл for, строки.

    Условные конструкции и цикл while. Работа с текстовыми файлами. (22 апреля)

    • Видеозаписи занятий и ipynb-файлы.
    • Альтернативы циклу for (читать, ipynb). Условные конструкции (читать). Цикл while (читать, скачать).
    • Чтение и запись текстовых файлов (читать, ipynb), файл intro.txt.
    • Практикум 3 (читать, ipynb), решения (читать, ipynb).
    • Практикум 4 (читать, ipynb), решения (читать, ipynb), файл ducks.txt.
    • Pythontutor: условия, цикл while.

    Множества и словари (29 апреля)

    • Видеозаписи занятий и ipynb-файлы.
    • Множества (читать). Словари и методы на словарях (читать, ipynb).
    • Практикум 5 (читать, ipynb), решения (читать, ipynb).

    Введение в парсинг с BeautifulSoup (13 мая)

    • Практикум 6 (читать, скачать), решения практикума (читать, скачать).

    Функции в Python. Lambda-функции (20 мая)

    • Видеозаписи занятий и ipynb-файлы.
    • Функции (читать, ipynb). Более подробная лекция по функциям (автор И.В.Щуров).
    • Lambda-функции (читать, ipynb).
    • Исключения и конструкция try-except (читать, скачать).
    • Практикум 7 (читать, скачать), решения (читать, скачать).

    Массивы NumPy и датафреймы Pandas (27 мая)

    • Видеозаписи занятий и ipynb-файлы.
    • Массивы и датафреймы pandas: введение (читать, ipynb).
    • Операции с датафреймами pandas (читать, ipynb), файл Salaries.csv.
    • Pandas, scipy и проверка гипотез читать, ipynb, файл NPK.xlsx.

    Более продвинутые примеры парсинга и работа с API на примере ВКонтакте (3 июня)

    • Видеозаписи и ipynb-файлы.
    • Примеры парсинга данных в псевдотабличном виде (читать, ipynb).
    • Примеры парсинга с BeautifulSoup и Pandas (читать, ipynb).
    • Инструкция по получению доступа к API ВКонтакте.
    • Практикум по выгрузке постов со стены сообщества (читать, ipynb).

    Более продвинутые примеры парсинга и библиотека Selenium (10 июня)

    • Видеозаписи и ipynb-файлы.
    • Краткое введение в регулярные выражения (читать, ipynb).
    • Парсинг HTML, обработка JSON и регулярные выражения (читать,ipynb).
    • Инструкция по установке драйверов для Chrome, ссылка на драйвера.
    • Практикум по парсингу с библиотекой Selenium (читать, ipynb).
    • Неофициальная документация библиотеки Selenium.
    • Управление браузером с Selenium на примере ВКонтакте (читать, скачать).
    • Управление браузером с Selenium: XPATH и скачивание файлов (читать, скачать).
    • Управление браузером с Selenium: пример динамической страницы (читать, скачать).

    Классы в Python. Веб-приложения со streamlit. (17 июня)

    • Видеозаписи и ipynb-файлы.
    • Классы в Python (читать, ipynb).
    • Веб-приложения со streamlit.

    Домашние задания

    • Домашние задания сдаются через систему python.math-info.
    Домашнее задание Дедлайн
    Домашнее задание 1 15 апреля 23:59
    Домашнее задание 2 25 апреля 23:59
    Домашнее задание 3, файл pesem.txt 2 мая 23:59
    Домашнее задание 4 14 мая 23:59
    Домашнее задание 5 6 июня 23:59
    Домашнее задание 6 10 июня 23:59
    Домашнее задание 7* 22 июня 23:59

    Create and edit Jupyter notebooks

    To open an existing .ipynb file, follow the same steps as for the files of the other types. If needed, you can create a notebook file.

    Create a notebook file

    1. Do one of the following:
      • Right-click the target directory in the Project tool window, and select New from the context menu.
      • Press Alt+Insert
    2. Select Jupyter Notebook .
    3. In the dialog that opens, type a filename.

    A notebook document has the *.ipynb extension and is marked with the corresponding icon.

    Editing Jupyter notebooks

    You can apply various editing actions to one cell or to the entire notebook. Press the Control+A once to select a cell at caret, and press Control+A twice to select all cells in the notebook.

    When editing notebook files, mind that PyCharm updates the source code and the preview of the notebook if it has been changed externally.

    The editor for Jupyter notebooks has two modes: the edit mode and the command mode . Depending on the mode you can either edit code in notebook cells or use keyboard shortcuts to perform specific actions with cells.

    Edit mode

    A cell in the edit mode

    • To toggle the edit mode, press Enter or click any cell.
    • When a cell is in the edit mode, it has a green border on the left and a highlighted line with a caret.
    • When in the edit mode, you can navigate through all cells line by line using Up / Down keys.

    Command mode

    A cell in the command mode

    • To toggle the command mode, press Esc or click the gutter.
    • When a cell is in the command mode, it has a blue border on the left.
    • When in the command mode, you can navigate the notebook cell by cell using Up / Down keys, as well as use keyboard shortcuts to select, copy, paste, and delete cells.

    Edit cells

    Select a cell type

    • A newly created notebook contains one code cell. You can change its type with the cell type selector in the notebook toolbar:
    • To edit a code cell, just click it.
    • To edit a Markdown cell, double-click it and start typing. To preview the output, press Shift + Enter .

    Working with notebook cells

    Add cells

    Adding a notebook cell

    • To add a code cell above the selected cell, do one of the following:
      • In the edit mode, press Alt+Shift+A .
      • In the command mode, press A .
      • Select Cell | Add Code Cell Above in the main menu.
    • To add a code cell below the selected cell, do one of the following:
      • In the edit mode, press Alt+Shift+B .
      • In the command mode, press B .
      • Select Cell | Add Code Cell Below in the main menu.
      • Click in the notebook toolbar.
    • You can add code or Markdown cells by using the popup between cells:

      Select cells

      • To select a cell, click the gutter next to the cell.
      • To select several cells:
        • Click the gutter next to cells while holding Shift for a series of consecutive cells, or Control for non-consecutive cells.
        • In command mode, press Shift and Up / Down keys.

        You can execute, copy, merge, and delete the selected cells.

        Copy and paste cells

        • To copy a cell in the command mode, press Control+C , C , or click on the notebook toolbar.
        • To paste the copied cell below, press Control+V , V , or click .
        • To paste it above the current cell, press Shift with Control+V / Shift+V .

        Split and merge cells

        • To merge a current cell with the cell below, right-click the cell and select Merge Cell Below command from the context menu. Similarly, you can merge a cell above the selected cell with the corresponding command.

        Delete cells

        • In the command mode, press D, D or Delete .
        • Click on the notebook editor toolbar.
        • Right-click the cell and select Delete Cell from the context menu.

        Use coding assistance

        You can edit code cells with the help of Python code insights, such as syntax highlighting, code completion, and so on.

          PyCharm enables code completion for the names of classes, functions, and variables. Start typing the name of the code construct, and the suggestion list appears.

        Function completion

        Class variable completion

        Path completion

        Package completion

        DataFrame column name completion

        The auto-completion of DataFrame columns names is available in runtime. PyCharm will suggest the names for columns only if the cell where the DataFrame is created has already run in the current kernel session.

        Quick-fix for the missing import

      • Intention actions and quick fixes. You can add the missing imports on-the-fly by using the intention actions. Note that you can add an import statement to the current cell or to the first cell of the notebook.

      Jupyter notebooks in PyCharm

      Today we’re going on a Python adventure using Jupyter notebooks and PyCharm! First, let’s talk about what these are. Jupyter Notebook is a web application where you can create interactive coding documents, supporting many programming languages including both Python and R as well as Markdown. PyCharm is an amazing IDE (interactive development environment) for Python that has tools and plugins to help you code more efficiently. You can develop your code both locally and remotely using PyCharm. First, let’s get set up!

      Getting started with PyCharm

      1. Install PyCharm.I highly recommend installing PyCharm Professional because you get more features like SciView that are awesome for data science. Plus PyCharm Professional is free for students!
      2. Install Python if you don’t already have it — you’ll need an interpreter in order to use PyCharm! Be aware that Python 2 and Python 3 are different in terms of syntax — don’t worry, you can load either version in PyCharm when you start a new project. If this is your first time developing in Python, I recommend going with the latest version 3.8.3.
      3. Create a new project in PyCharm and select your local Python interpreter. Here, I created a new project called ‘pycharm’ in a directory on my desktop and selected Python 3.7 as my interpreter.

      1. Install Jupyter by selecting PyCharm >> Preferences >> Project Interpreter, then click the “+” button to add new packages.

      Then type ‘jupyter’ and select jupyter from the packages list. Then click the ‘Install Package’ button at the bottom of the window.

      1. Create a new Jupyter notebook by navigating to File >> New… and selecting ‘Jupyter Notebook’. Alternatively, if you just want to create a Python script you can select ‘Python File’. Here, I created a new notebook called pycharm.ipynb.

      1. Let’s start editing our notebook by adding a Markdown cell. In the editor next to the ‘#%’, add ‘md’ to set the cell type to Markdown. Then use Markdown formatting, such as ‘### Header’ like in my example here. Notice that the right side panel displays a preview of your notebook.

      1. Now let’s add a coding cell. Click the ‘+’ button just below the Markdown cell to add a new cell. Add your code and click the green arrow to run the code in the cell.

      Here I created and printed a variable called my_string.

      1. Let’s check out a cool feature of PyCharm Scientific View. Add the following to a code cell and run it:
      import pandas as pd #read in data from my github repo data = pd.read_csv("https://raw.githubusercontent.com/CaitlinCasar/Casar2020_DeMMO_MineralHostedBiofilms/master/orig_data/site_geochem.csv") data.head()
      1. Next, open your Jupyter tab at the bottom of your PyCharm window, click on the variables tab, and right click on the new variable you just created called ‘data’. Select ‘View as Dataframe’, then click on the ‘SciView’ tab on the right panel.

      This is a great feature for viewing your stored variables. You can view both dataframes and arrays with SciView.

      1. Let’s try launching this notebook in our browser. Click on the text at the bottom of your PyCharm window that says “Jupyter Server started at http://localhost:8888// Open in Browser”. You should see an Event Log window pop up in the bottom right panel. Click on “Open in Browser” to launch your notebook in your web browser.

      You should now see something like this in your browser:

      Click on the notebook to run your code in the browser window. You can run cells by clicking the Run button in the top tool bar, or by clicking Ctrl + Enter.

      Sync files with a remote server

      1. Let’s say you want to sync files on a remote server. You’ll need to set up your file transfer protocol. Select Tools >> Deployment >> Browse Remote Host. Then select your protocol — here I chose SFTP (secure file transfer protocol).

      1. Next, configure your connection to the remote host by adding your IP address and log in credentials. Optionally, set your root path to the path on the remote server where you want to access files.

      1. Click on the Mapping tab and set your local path to your project directory in PyCharm. Set the deployment path to the directory on the remote server where you want to access or upload files.

      1. Sync your local directory with the remote directory by right-clicking on your project in the left panel, then select Deployment >> Sync with Deployed To…

      Then click the green double arrow button “Synchronize All” to sync your files. You can use the ‘Remote Host’ tab on the right panel to view your remote file tree.

      Run a remote Jupyter server kernel

      If you want to run an interactive Jupyter notebook on a remote server in PyCharm, you’ll need to set up your Jupyter server configuration and remote Python interpreter.

      1. In the terminal, SSH into your remote server, navigate to the directory where your data is, then launch a Jupyter notebook.

      1. Navigate to the directory where your data is located. Then launch a jupyter notebook by running the following:
      #replace port number with whatever port you want jupyter notebook --port=8899 --no-browser

      This will return a url and token, similar to:

      https://my-notebook/tree/?token=abcdef. 

      Copy this entire url and token. Make sure you copy it all from one line — I have to make my terminal full screen for this. Otherwise you might get a weird line break and your url/token might not work.

      1. Open a new Jupyter notebook file and select ‘Configure jupyter server…’.

      Paste your url and token in the field for ‘Configured Server’. Then click ‘Apply’.

      1. You should now be able to access data on the remote server in your Jupyter notebook. Here, I cloned my repo on the remote server, and I’m accessing a csv file with the pandas library.

      1. If you want to use an interpreter on the remote server, you can figure the interpreter by naviating to Pycharm >> Preferences >> Project Interpreter…, then select the wheel button next to your current interpreter and select ‘Add…’. Then select ‘SSH interpreter’ and choose ‘Existing server configuration’. From the dropdown menu, select the SSH configuration that you set up in step 2 of the ‘Sync files with a remote server’ above.

      Note:Unfortunately, you cannot view your variables while using a remote Jupyter server kernel as documented here.

      Congrats on developing in Jupyter Notebooks and PyCharm! I hope you enjoyed this tutorial, feel free to comment below with any comments/questions! ��

      Jupyter notebook support

      With Jupyter Notebook integration available in PyCharm , you can easily edit, execute, and debug notebook source code and examine execution outputs including stream data, images, and other media.

      Notebook support in PyCharm includes:

      • Coding assistance:
        • Error and syntax highlighting.
        • Code completion.
        • Ability to create line comments Control+/ .

        Quick start with the Jupyter notebook in PyCharm

        To start working with Jupyter notebooks in PyCharm:

        1. Create a new Python project, specify a virtual environment, and install the jupyter package.
        2. Open or create an .ipynb file.
        3. Add and edit source cells.
        4. Execute any of the code cells to launch the Jupyter server.

        Get familiar with the user interface

        Mind the following user interface features when working with Jupyter notebooks in PyCharm.

        Notebook editor

        Overview of the editor UI

        A Jupyter notebook opened in the editor has its specific UI elements:

        • Jupyter notebook toolbar : provides quick access to the most popular actions. The rest of the notebook-specific actions are available in the Cell menu.
        • Code cell : a notebook cell that contains an executable code
        • Cell output : results of the code cell execution; can be presented by a text output, table, or plot.

        Notebook toolbar

        The Jupyter notebook toolbar provides quick access to all basic operations with notebooks:

        Jupyter toolbar

        Adds a code cell below the selected cell.

        Moves the selected item or items from the current location to the clipboard. Moves the entire cell if it’s selected.

        Copies the selected item or items to the clipboard. Copies the entire cell if it’s selected.

        Inserts the contents of the clipboard into the selected location. If you’ve selected an entire cell, the contents are pasted to a new cell below the selected one.

        Moves the current cell up.

        Moves the current cell down.

        Executes this cell and selects a cell below. If there is no a cell below, PyCharm will create it.

        Starts debugging for this cell.

        Click this icon if you want to interrupt any cell execution.

        Executes all cells in the notebook.

        You can select a cell type from this list and change the type for the selected cell.

        Deletes the current cell.

        List of Jupyter servers

        The Jupyter Server widget that shows the currently used Jupyter server. Click the widget and select Configure Jupyter Server to setup another local or remote Jupyter server.

        List of Jupyter kernels

        List of the available Jupyter kernels.

        Select this checkbox to allow executing JavaScript in your Jupyter notebook.

        This actions selects the cell above.

        This actions selects the cell blow.

        You can preview the notebook in a browser.

        Tool windows

        The Server Log tab of the Jupyter tool window appears when you have any of the Jupyter server launched. The Server log tab of this window shows the current state of the Jupyter server and the link to the notebook in a browser.

        Jupyter server tool window: the Server log tab

        It also provides controls to stop the running server () and launch the stopped server ().

        The Jupyter Variables tool window the detailed report about variable values of the executed cell.

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

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