Скрипты python для power bi

Use Python in Power Query Editor

You can use Python, a programming language widely used by statisticians, data scientists, and data analysts, in the Power BI Desktop Power Query Editor. This integration of Python into Power Query Editor lets you perform data cleansing using Python, and perform advanced data shaping and analytics in datasets, including completion of missing data, predictions, and clustering, just to name a few. Python is a powerful language, and can be used in Power Query Editor to prepare your data model and create reports.

Prerequisites

You’ll need to install Python and pandas before you begin.

  • Install Python — To use Python in Power BI Desktop’s Power Query Editor, you need to install Python on your local machine. You can download and install Python for free from many locations, including the Official Python download page, and the Anaconda.
  • Install pandas — To use Python with the Power Query Editor, you’ll also need to install pandas. Pandas is used to move data between Power BI and the Python environment.

Use Python with Power Query Editor

To show how to use Python in Power Query Editor, take this example from a stock market dataset, based on a CSV file that you can download from here and follow along. The steps for this example are the following procedure:

  1. First, load your data into Power BI Desktop. In this example, load the EuStockMarkets_NA.csv file and select Get data >Text/CSV from the Home ribbon in Power BI Desktop. Screenshot of the Get Data ribbon in Power BI Desktop, showing the CSV selection.
  2. Select the file and select Open, and the CSV is displayed in the CSV file dialog. Screenshot of the CSV file dialog, showing the selected CSV.
  3. Once the data is loaded, you see it in the Fields pane in Power BI Desktop. Screenshot of the Fields pane, showing the loaded data.
  4. Open Power Query Editor by selecting Transform data from the Home tab in Power BI Desktop. Screenshot of the Power Query Editor in Power BI Desktop, showing the Transform data selection.
  5. In the Transform tab, select Run Python Script and the Run Python Script editor appears as shown in the next step. Rows 15 and 20 suffer from missing data, as do other rows you can’t see in the following image. The following steps show how Python completes those rows for you. Screenshot of the Transform tab, showing rows of data.
  6. For this example, enter the following script code:
import pandas as pd completedData = dataset.fillna(method='backfill', inplace=False) dataset["completedValues"] = completedData["SMI missing values"] 

Note You need to have the pandas library installed in your Python environment for the previous script code to work properly. To install pandas, run the following command in your Python installation: pip install pandas

When put into the Run Python Script dialog, the code looks like the following example: Screenshot of the Run Python Script dialog, showing the script code.

  • After you select OK, Power Query Editor displays a warning about data privacy. Screenshot of the Power Query Editor pane, showing the warning about data privacy.
  • For the Python scripts to work properly in the Power BI service, all data sources need to be set to public. For more information about privacy settings and their implications, see Privacy Levels. Screenshot of the Privacy levels dialog, showing that Public is set.Notice a new column in the Fields pane called completedValues. Notice there are a few missing data elements, such as on row 15 and 18. Take a look at how Python handles that in the next section.
  • With just three lines of Python script, Power Query Editor filled in the missing values with a predictive model.

    Create visuals from Python script data

    Now we can create a visual to see how the Python script code using the pandas library completed the missing values, as shown in the following image:

    Screenshot of the visual, showing original data and completed missing values of the pandas library.

    Once that visual is complete, and any other visuals you might want to create using Power BI Desktop, you can save the Power BI Desktop file. Power BI Desktop files save with the .pbix file name extension. Then use the data model, including the Python scripts that are part of it, in the Power BI service.

    Want to see a completed .pbix file with these steps completed? You’re in luck. You can download the completed Power BI Desktop file used in these examples right here.

    Once you upload the .pbix file to the Power BI service, a couple more steps are necessary to enable data to refresh in the service and to enable visuals to be updated in the service. The data needs access to Python for visuals to be updated. The other steps are the following steps:

    • Enable scheduled refresh for the dataset. To enable scheduled refresh for the workbook that contains your dataset with Python scripts, see Configuring scheduled refresh, which also includes information about Personal Gateway.
    • Install the Personal Gateway. You need a Personal Gateway installed on the machine where the file is located, and where Python is installed. The Power BI service must access that workbook and re-render any updated visuals. For more information, see install and configure Personal Gateway.

    Considerations and limitations

    There are some limitations to queries that include Python scripts created in Power Query Editor:

    • All Python data source settings must be set to Public, and all other steps in a query created in Power Query Editor must also be public. To get to data source settings, in Power BI Desktop select File > Options and settings > Data source settings. Screenshot of the File menu in Power BI Desktop, showing the Data source settings selection.From the Data Source Settings dialog, select the data sources and then select Edit Permissions. and ensure that the Privacy Level is set to Public. Screenshot of the Data source settings dialog, showing the Privacy Level is set to Public.
    • To enable scheduled refresh of your Python visuals or dataset, you need to enable Scheduled refresh and have a Personal Gateway installed on the computer that houses the workbook and the Python installation. For more information on both, see the previous section in this article, which provides links to learn more about each.
    • Nested tables, which are table of tables, are currently not supported.

    There are all sorts of things you can do with Python and custom queries, so explore and shape your data just the way you want it to appear.

    Feedback

    Submit and view feedback for

    Источник

    Запустить сценарий Python в Power BI Desktop

    Вы можете выполнять скрипты Python непосредственно в Power BI Desktop и импортировать полученные наборы данных в модель данных Power BI Desktop. На основе этой модели можно создавать отчеты и передавать их в службу Power BI для общего доступа.

    Предварительные требования

    • Для запуска сценариев Python в Power BI Desktop необходимо установить Python на локальном компьютере. Скачать Python можно с веб-сайта Python. В текущем выпуске скриптов Python поддерживаются символы Юникода и пробелы в пути установки.
    • Для интеграции Power BI с Python требуется установка следующих двух пакетов Python. В консоли или оболочке используйте программу командной строки pip для установки пакетов. Средство pip упаковано с последними версиями Python.
      • Pandas — это библиотека программного обеспечения для обработки и анализа данных. Pandas предлагает структуры данных и операции для управления числовыми таблицами и временными рядами. Для импорта в Power BI данные Python должны находиться в кадре данных Pandas. Кадр данных — это двумерная структура данных, например таблица со строками и столбцами.
      • Matplotlib — это библиотека построения графиков для Python и его расширение numPy для числовой математики. Matplotlib предоставляет объектно-ориентированный API для внедрения графиков в приложения графического пользовательского интерфейса общего назначения (GUI) для Python, такие как Tkinter, wxPython, Qt или GTK+.
      pip install pandas pip install matplotlib 

      Включение скриптов Python

      Чтобы включить скрипты Python в Power BI, выполните следующие действия.

      Снимок экрана: параметры скрипта Python для Power BI Desktop.

      1. В Power BI Desktop последовательно выберите Файл>Параметры и настройки>Параметры>Создание скриптов Python. Откроется страница Параметры скриптов Python.
      2. При необходимости укажите или измените локальный путь установки Python в разделе Обнаруженные домашние каталоги Python. На предыдущем рисунке локальный путь установки Python — C:\Python. Если у вас есть несколько локальных установок Python, обязательно выберите ту, которую вы хотите использовать.
      3. Щелкните ОК.

      Power BI запускает скрипты непосредственно с помощью исполняемого файлаpython.exe из каталога, который вы указали в разделе Параметры. Дистрибутивы Python, требующие дополнительного шага для подготовки среды, например Conda, могут завершиться сбоем. Чтобы избежать этих проблем, используйте официальный дистрибутив Python из https://www.python.org. Другим возможным решением является запуск Power BI Desktop из пользовательской командной строки среды Python.

      Создание скрипта Python

      Создайте скрипт в локальной среде разработки Python и убедитесь, что он успешно выполняется. Для подготовки и запуска скрипта Python в Power BI Desktop существует несколько ограничений.

      • Импортируются только кадры данных Pandas, поэтому убедитесь, что данные, которые вы хотите импортировать в Power BI, представлены в кадре данных.
      • Время ожидания любого скрипта Python, выполняющегося дольше 30 минут, истекает.
      • Интерактивные вызовы в скрипте Python, такие как ожидание ввода данных пользователем, приостанавливают выполнение скрипта.
      • Если вы задали рабочий каталог в скрипте Python, необходимо определить полный путь к рабочему каталогу, а не относительный путь.
      • Вложенные таблицы не поддерживаются.

      Ниже приведен простой пример скрипта Python, который импортирует Pandas и использует кадр данных:

      import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13]] df = pd.DataFrame(data,columns=['Name','Age'],dtype=float) print (df) 

      При запуске этот скрипт возвращает:

       Name Age 0 Alex 10.0 1 Bob 12.0 2 Clarke 13.0 

      Запуск скрипта и импорт данных

      Чтобы запустить скрипт Python, выполните следующие действия.

      1. В группе Главная на ленте Power BI Desktop выберите Получить данные.
      2. В диалоговом окне Получение данных выберите Другой>скрипт Python, а затем щелкните Подключиться. Power BI использует последнюю установленную версию Python в качестве подсистемы Python. Снимок экрана: получение данных с выбранным скриптом Python.
      3. На экране Скрипт Python вставьте скрипт Python в поле Скрипт и нажмите кнопку ОК. Снимок экрана: вставка примера скрипта Python в диалоговое окно скрипта Python.
      4. Если скрипт выполняется успешно, появится окно Навигатор , и вы сможете загрузить данные. Выберите таблицу df , а затем щелкните Загрузить. Снимок экрана: окно навигатора с данными для загрузки и использования.

      Power BI импортирует данные, и их можно использовать для создания визуализаций и отчетов. Чтобы обновить данные, выберите Обновить в группе Главная ленты Power BI Desktop. При обновлении Power BI снова запустит скрипт Python.

      Если Python не установлен или не определен, появится предупреждение. Кроме того, при наличии нескольких установок на локальном компьютере может появиться предупреждение.

      Снимок экрана: предупреждение о том, что Python не установлен.

      Дальнейшие действия

      Дополнительные сведения о Python в Power BI см. в статье:

      Источник

      Читайте также:  Тег IMG
    Оцените статью