power bi python скрипт
Create Power BI visuals by using Python
With Power BI Desktop, you can use Python to visualize your data.
Prerequisites
Work through the Run Python scripts in Power BI Desktop tutorial using the following Python script:
The Run Python scripts in Power BI Desktop article shows you how to install Python on your local machine and enable it for Python scripting in Power BI Desktop. This tutorial uses data from the above script to illustrate creating Python visuals.
Create Python visuals in Power BI Desktop
Select the Python visual icon in the Visualizations pane.
In the Enable script visuals dialog box that appears, select Enable.
When you add a Python visual to a report, Power BI Desktop takes the following actions:
A placeholder Python visual image appears on the report canvas.
The Python script editor appears along the bottom of the center pane.
Next, drag the Age, Children, Fname, Gender, Pets, State, and Weight fields to the Values section where it says Add data fields here.
Your Python script can only use fields added to the Values section. You can add or remove fields from the Values section while working on your Python script. Power BI Desktop automatically detects field changes.
The default aggregation type for Python visuals is do not summarize.
Now you can use the data you selected to create a plot.
As you select or remove fields, supporting code in the Python script editor is automatically generated or removed.
Based on your selections, the Python script editor generates the following binding code.
In certain cases, you might not want automatic grouping to occur, or you’ll want all rows to appear, including duplicates. If so, you can add an index field to your dataset that causes all rows to be considered unique and which prevents grouping.
You can access columns in the dataset using their respective names. For example, you can code dataset[«Age»] in your Python script to access the age field.
With the dataframe automatically generated by the fields you selected, you’re ready to write a Python script that results in plotting to the Python default device. When the script is complete, select Run from the Python script editor title bar.
Power BI Desktop replots the visual if any of the following events occur:
When you run a Python script that results in an error, the Python visual isn’t plotted and a canvas error message appears. For error details, select See details from the message.
To get a larger view of the visualizations, you can minimize the Python script editor.
Ok, let’s create some visuals.
Create a scatter plot
Let’s create a scatter plot to see if there’s a correlation between age and weight.
Under Paste or type your script code here, enter this code:
Your Python script editor pane should now look like this:
The matplotlib library is imported to plot and create our visuals.
When you select the Run script button, the following scatter plot generates in the placeholder Python visual image.
Create a line plot with multiple columns
Let’s create a line plot for each person showing their number of children and pets. Remove or comment the code under Paste or type your script code here and enter this Python code:
When you select the Run script button, the following line plot with multiple columns generates.
Create a bar plot
Let’s create a bar plot for each person’s age. Remove or comment the code under Paste or type your script code here and enter this Python code:
When you select the Run script button, the following bar plot generates:
Security
Python scripts security: Python visuals are created from Python scripts, which could contain code with security or privacy risks. When attempting to view or interact with an Python visual for the first time, a user is presented with a security warning message. Only enable Python visuals if you trust the author and source, or after you review and understand the Python script.
More information about plotting with Matplotlib, Pandas, and Python
This tutorial is designed to help you get started creating visuals with Python in Power BI Desktop. It barely scratches the surface about the many options and capabilities for creating visual reports using Python, Pandas, and the Matplotlib library. There’s a lot more information out there, and here are a few links to get you started.
Known limitations
Python visuals in Power BI Desktop have a few limitations:
Next steps
Take a look at the following additional information about Python in Power BI.
Python visualizations in Power BI Service
With our February update of Power BI, you can now share, publish and view Python visuals in your reports and dashboards. This update extends the support for Python in the Power BI Desktop to the Power BI service.
This ability completes the support for Python in Power BI, enabling you to use Python scripts to prepare your dataset, apply sophisticated analytics or machine learning in the Power BI Desktop & personal gateway, and then plot the results in your Power BI reports using any of the hundreds of open-source Python visualization packages. Publishing your reports to the Power BI service will automatically refresh these visuals with the latest data when a user views the report. Just like the support for R visualizations in Power BI, your Python visualizations will update with cross-filtering in the report, but the visuals are not interactive.
Publishing Power BI reports with Python visuals
You can add a Python visual to your Power BI report by selecting the Python visual icon from the Visualizations pane in the Power BI Desktop, which adds a placeholder Python script to the report. Adding the fields from your dataset to the Values pane of the Python visual, automatically adds the fields to the pandas DataFrame in the placeholder Python script. You can then use the Python script to create the visualization you’d like. See Create Power BI visuals using Python for instructions.
When you publish the report the report to your Power BI workspace, the visuals are automatically refreshed when the report is viewed. Note, there are a few constraints on the size of the serialized Python dataframe, and the execution resources used by the Python scripts, that are summarized below.
Python packages and versions
The initial version of the Python runtime supported in Power BI includes versions 2.7.15 and 3.7.1. We will periodically update the runtime to keep it current.
The following Python packages (non-Intel MKL) are currently supported for use in your Power BI reports:
We’ll include the versions of the packages supported in the documentation for the Python support in Power BI.
Security and execution constraints
The Python scripts in your reports are executed by the Power BI service in an isolated sandbox that restricts the access of the scripts to the network and the other machine resources. This ensures that your datasets and the Power BI service are not vulnerable to attacks.
The Power BI service also imposes other limits on Python script execution.
Constraint | Limit |
---|---|
Dataframe size | 150,000 rows 250MB when serialized in CSV format |
Execution time | 60 seconds |
Memory consumption | 1 GB |
Disk I/O | 1 GB/sec |
Image size for a visual in PNG format | 2 MB |
These limits ensure that user-provided scripts are performant, and moderate in the consumption of resources.
These constraints apply to the execution of Python scripts in Power BI service. Python script execution on the Power BI Desktop and personal gateway has the same dataframe size and PNG image size limits, but the execution time limit is 300 seconds. Other constraints are not applicable to Power BI Desktop and personal gateway.
Python support in Power BI personal gateway
Python can be used for data preparation or for analytics in your Power BI reports, either with a Python script data connector or by using a Python script in the Power Query editor for data transformation.
When you publish a Power BI report with Python scripts to the service, these scripts will also be executed when your data is refreshed through the on-premises data gateway in personal mode (personal gateway).
To enable this, you must ensure that the Python runtime with the dependent Python packages are also installed on the machine hosting your personal gateway. Note, Python script execution is not supported for on-premises data gateways shared by multiple users.
Sample files
A version of the Power BI file with sample Python visuals from the earlier post, updated for publishing to the Power BI service is available here.
If you have any questions, you can post them on the community forums, or you can reach me at @santoshc1. We’d love to hear your feedback and ideas. Hope you enjoy scripting with Python in Power BI!
Запустить сценарий Python в Power BI Desktop
Вы можете выполнять скрипты Python непосредственно в Power BI Desktop и импортировать полученные наборы данных в модель данных Power BI Desktop.
Установка Python
Для запуска сценариев Python в Power BI Desktop необходимо установить Python на локальном компьютере. Скачать Python можно с веб-сайта Python. В текущем выпуске скриптов Python поддерживаются символы Юникода и пробелы в пути установки.
Установка необходимых пакетов Python
Для интеграции Power BI с Python требуется установить два пакета Python:
В консоли или оболочке используйте для установки этих двух пакетов программу командной строки pip. Средство pip входит в состав последних версий Python.
Включение скриптов Python
Включение скриптов Python:
В Power BI Desktop последовательно выберите Файл > Параметры и настройки > Параметры > Создание скриптов Python. Откроется страница Параметры скриптов Python.
При необходимости укажите локальный путь установки Python в разделе Обнаруженные домашние каталоги Python.
На приведенном выше рисунке используется следующий локальный путь установки Python: C:\Python. Путь должен соответствовать расположению каталога с локальной установленной версией Python, которая будет использоваться службой Power BI Desktop.
Выберите ОК.
После указания установленной версии Python все готово к выполнению скриптов Python в Power BI Desktop.
Запустить сценарии Python
Для запуска скриптов Python и создания модели данных достаточно выполнить несколько шагов. На основе этой модели можно создавать отчеты и передавать их в службу Power BI для общего доступа.
Подготовка сценария Python
Создайте скрипт в локальной среде разработки Python и убедитесь, что он выполняется успешно. Ниже приводится пример простого скрипта Python, который импортирует pandas и использует кадр данных:
При запуске этот скрипт возвращает:
При подготовке и выполнении сценариев Python в Power BI Desktop действуют некоторые ограничения.
Выполнение сценария Python и импорт данных
Выполнение скрипта Python в Power BI Desktop:
На вкладке ленты «Главная» выберите Получить данные > Другое.
Выберите Другое > Скрипт Python, как показано на следующем рисунке:
Нажмите кнопку Подключиться. В качестве подсистемы Python выбирается локальная самая новая установленная версия Python. Скопируйте скрипт в появляющееся диалоговое окно Скрипт Python. Здесь мы вводим простой скрипт Python, показанный ранее.
Выберите ОК. Если скрипт успешно выполняется, появляется окно Навигатор, в котором вы можете загрузить и использовать данные. Например, установите флажок df, как показано на следующем рисунке, после чего выберите Загрузить.
Устранение неполадок
Если средство Python не установлено или не определено, отображается предупреждение. Кроме того, может отображаться предупреждение о наличии нескольких установленных версий на локальном компьютере. Снова ознакомьтесь с ранее приведенными разделами «Установка Python» и «Включение скриптов Python».
Использование пользовательских дистрибутивов Python
Power BI выполняет скрипты напрямую с помощью исполняемого файла python.exe из каталога, указанного пользователем на странице параметров. Выполнение дистрибутивов, требующих дополнительного шага для подготовки среды (например, Conda), может завершаться сбоем.
Во избежание таких проблем мы рекомендуем использовать официальный дистрибутив Python с сайта https://www.python.org/.
В качестве возможного решения вы можете запустить Power BI Desktop из командной строки пользовательской среды Python.
Обновить
Вы можете обновить сценарий Python в Power BI Desktop. Чтобы выполнить обновление, перейдите на вкладку ленты Главная и выберите Обновить. При обновлении скрипта Python служба Power BI Desktop запускает его повторно.
Известные ограничения
Дальнейшие действия
Ознакомьтесь с дополнительными материалами по Python в Power BI.
Поиск
Предисловие
После установки августовского релиза Power BI я очень обрадовался, увидев поддержку Python. Как раз в работе оказался проект, в котором возможность поддержки Python помогла реализовать требования заказчика. Нужно было подключаться к API, предварительно зашифровывая тело запроса открытым и закрытым ключём, перед отправлением запроса к API. К сожалению, как оказалось, поддержка шифрования в Power BI есть только в кастомных дата коннекторах, и отсутствует в Power Query для Power BI Desktop. А при всем моем теплом отношении к языку R, связываться с ним лишний раз, мне бы не хотелось. Поэтому поддержке Python в Power BI я был рад очень.
Задача
Демонстрационный отчет в Power BI Online
Описание решения
Предварительные требования
Подготовка в Power BI
Разработка скрипта Python
В моем примере скрипт на Python будем разрабатывать в инструменте, популярном у аналитиков данных Jupyter Notebook.
В рамках рассмотренного примера для простоты работы внутри скрипта на Python вручную создается таблица, а затем с помощью переданных параметров таблица отфильтровывается. Полученный результат далее возвращается в Power BI и может использоваться для дальнейшего анализа.
Если вам нужно настроить преобразование строки под ваш формат даты времени, то вы можете использовать для этого таблицу кодов форматов для 2 или 3 Питона соответственно.
Средствами Jupyter Notebook мы можем отладить и проверить полученные данные перед копированием полученного сприпта в Power BI.
В результате получаем скрипт, подготовленный для передачи в Power BI
Вызов скрипта на Python из Power BI
Обратите внимание на то, что все наше красивое форматирование в python Power BI Desktop собрал в одну строку. Так что если далее потребуется дорабатывать наш скрипт мы вернемся в Jupyter и последовательно проделаем шаги: исправим, отладим и так же передадим его через буфер обмена в Power BI Desktop.
Материалы
Для удобства исследования статьи привожу готовый файл срипта и пример на Power BI:
Обсуждение решения
Старший BI разработчик
Бизнес аналитика, функциональное программирование и машинное обучение.
Поддержка Python в Power BI
Мы рады сообщить, что Python, язык программирования, широко используемый статистиками, учеными и аналитиками, теперь интегрирован в наш бесплатный Power BI Desktop. После включения функции в настройках вы cможете использовать Python для очистки, анализа и визуализации данных. Подробнее под катом!
Первой интеграционной фичей, которую мы добавили, является возможность запуска скриптов Python непосредственно в Power BI Desktop для создания модели данных. Вы можете это сделать в диалоговом окне «Получить данные».
После выбора этой опции вы сможете вставить свой скрипт.
Интеграция с редактором запросов позволяет проводить очистку данных с помощью Python и использовать продвинутые методы анализа ваших данных, включая, например, удаление миссингов, прогнозирование и кластеризацию.
Наконец, вы можете использовать Python для создания новых визуальных эффектов в своем отчете. Подобно визуализации в R, визуальные эффекты Python будут обновляться с обновлением данных и кросс-фильтрацией. Однако сам визуал пока интерактивным не является.
И это далеко не все
Это — лишь одно из огромного количества нововведений свежей версии Power BI. Обо всех новинках обновления вы можете узнать из этой статьи или из видео: