Power BI Python using Python import data in Power BI Desktop

As I have written a blog post, Power BI Python Python use in drawing in Power BI Desktop , today I use Python scripts to generate data Power Query of Queries

We generally use third-party IDE to debug the Python code, and then run in Power BI Desktop, I used here is Pycharm, as for all the IDE installation package to the Internet to find it.

 

We take a look at the contents of Python code:

image

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        'key1': list('aabba'),
        'key2': ['one', 'two', 'one', 'two', 'one'],
        'data1': np.random.randn(5),
        'data2': np.random.randn(5)
    });

print(df)

注意:最后一行print(df)并非是必需的,我只是为了在Pycharm编辑环境里查看下输出的结果而已,在贴到Power BI Desktop的时候并不需要该行。Power BI Desktop会得到Python代码中数据类型是DataFrame的变量数据。

 

接下来我们看看如何将代码贴入Power BI Desktop运行,操作可以通过2种方式,

其一:图形界面里找“Python脚本”选项,其二:空查询中使用Python.Execute()函数

 

“Python脚本”

我们首先看第一种运行方式:

1、在Power Query编辑器中依次点击“新建源/更多…”,随后依次选择“其它/Python脚本”,点击确定按钮,然后将Python代码贴入窗口文本框里。

image image

image

2、 点击确定按钮后,会打开导航器窗口,左侧会列出数据类型为DataFrame的变量,只有勾选了一项之后,右下角的确定按钮才变得可用

image

image

 

Python.Execute()函数

接下来我们来看第二种方式,直接在空查询中运行函数Python.Execute()函数

1、在Power Query管理器中依次点击“主页/新建源/空查询”,公式编辑栏输入Py,将会自动出现M函数列表智能提示(我是今天刚更新了Power BI Desktop,我之前的版本没有M语言的智能提示功能。)

image image

2、该函数,接受一个字符串参数,所以我们要用成对的双引号,然后再贴Python代码到里面,然后按下回车键,此时会出现“编辑权限”按钮,点击之后,弹出“脚本之行”对话框,点击运行按钮即可

image image

image

 

多个DataFrame变量

运行Python脚本后,Power BI会提取所有数据类型为DataFrame的变量出来,我们上面只有一个变量,那么我们改下代码来看看,

直接拷贝第一个变量,然后改下2个变量的名字

import pandas as pd
import numpy as np

df1 = pd.DataFrame(
    {
        'key1': list('aabba'),
        'key2': ['one', 'two', 'one', 'two', 'one'],
        'data1': np.random.randn(5),
        'data2': np.random.randn(5)
    });

df2 = pd.DataFrame(
    {
        'key1': list('aabba'),
        'key2': ['one', 'two', 'one', 'two', 'one'],
        'data1': np.random.randn(5),
        'data2': np.random.randn(5)
    });

Before that I will use Python.Execute () function in the formula above parameters directly replaced with the code, then you see the following results after running

image

Guess you like

Origin www.cnblogs.com/alexywt/p/11402877.html