这是一个自我回答的帖子。为什么?因为缺少数据样本,所以Power BI中的许多问题都无法回答。另外,许多人似乎想知道如何使用Python在Power BI中编辑数据表。当然,全世界都需要Power BI中Python的更广泛使用。有人认为您必须将Python代码段应用于其他位置加载的现有表。我对本文的回答将向您展示如何在原本为空的Power BI文件中用几行代码构建一个(相当大的)数据样本。
因此,如何在Power BI中使用Python构建数据样本并对其进行更改?
我将向您展示如何构建10000
包含分类值和数值的行的数据集。我将Python库numpy和pandas分别用于数据生成和表操作。下面的代码片段仅从两个列表10000
时间中绘制了一个随机元素,以构建带有一些街道和城市名称的两列,并将一个随机数列表添加到混合中。然后,我使用熊猫将数据组织到数据框中。在中使用Python Power BI Power Query Editor
,您的输入必须是表格,而输出则必须是pandas数据框。
Python片段:
import numpy as np
import pandas as pd
np.random.seed(123)
streets=['Broadway', 'Bowery', 'Houston Street']
cities=['New York', 'Chicago', 'Baltimore']
rows = 1000
lst_cities=np.random.choice(cities,rows).tolist()
lst_streets=np.random.choice(streets,rows).tolist()
lst_numbers= np.random.randint(low=0, high=100, size=rows).tolist()
df_dataset=pd.DataFrame({'City':lst_cities,
'Street':lst_streets,
'ID':lst_numbers})
df_metadata = pd.DataFrame([df_dataset.shape])
Power BI:
在Power BI Desktop中,单击Enter Data
以转到Power Query Editor
。在下面的对话框窗口中,除了单击,什么都不要做OK
。结果是一个空表和下面的两个步骤Applied steps
:
现在,使用Transform > Run Python Script
,在上面插入代码段,然后单击OK
以获取以下信息:
You now have a preliminary table with 2 columns and 3 rows. And this is a pretty neat detail of the implementation of Python in Power BI. These are three different datasets that are made available to you after running your snippet. Dataset
is constructed by default, but is empty since we started out with an empty table. If we started out with some other data, the first line of the Run Python Script
explains the purpose of this table # 'dataset' holds the input data for this script
. And it is constructed in the form of a pandas dataframe. The last table df_metadata
is only a brief description of the dataset we're really interested in: df_dataset
, but I've added it to the mix in order to illustrate that all dataframes made by you in your snippet will be available to you. You chose which table to continue working on by clicking Table
next to the name.
就是这样!现在,您有了一个混合数据类型表,可以继续使用Python或Power BI本身进行工作:
在这里您可以:
Reference
框,Table
并通过右键单击下的创建一个,继续使用其他版本Queries
:本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句