Edit python script used as Data entry in Power BI

Viewed 4136

I have a python script and used it to create a dataframe in Power BI.

Now I want to edit that dataframe in Power BI but don´t enter from scratch as new data because I want to keep all the charts inside my Power BI model.

For example in my old dataframe i specified some dates inside my script so the information was limited to those dates. Now i want to change the dates to new ones but dont want to lose all the model.

df = df

2 Answers

I hope you're not dong this in a PowerBI Python Visual. If you're using Python under the Transform tab in the Power Query Editor, the key to your problem lies not in Python itself, but rather in the reference function available to you if you right-click the table under queries in the Power Query Editor:

enter image description here

Try this:

1: Save the following sample data in a csv as C:\pbidata\src.csv file and load it into PowerBI using Get Data > Text/Csv

A,B,C
1,1*0,100
2,20,200
3,30,300

2: Display it as a table:

enter image description here

3: Open the Power Query Editor through Edit Queries

enter image description here

4: Add some Python

Here you can insert a Python snippet after the Changed type step under Applied steps with Transform > Run Python Script. Inserting the following example code:

# 'dataset' holds the input data for this script
import pandas as pd
df=dataset.copy(deep=True)
df['D']=df['C']*2

... will give you this:

enter image description here

5: And let's say that you're happy with this for now and that you'd like to make a plot out of it back on the Power BI Desktop. I'm using a clustered bar chart to get this:

enter image description here

6: Now, like you're saying, if you'd like to have df['D']=df['C']/4 instead, but retain the same dataset, Python script and figure Plot 1, Py script 1, go back to the Power Query Editor and use the functionality that I mentioned in the beginning:

enter image description here

7: And add another Python snippet:

# 'dataset' holds the input data for this script
import pandas as pd
df=dataset.copy(deep=True)
df['D']=df['D']/4

And there we go:

enter image description here

Now you have two different Python snippets that build on the same dataset. You still have the data from the first snippet, and you can do whatever you want with the second snippet without messing up your data source.

8: Insert another chart to verify:

enter image description here

9: Maybe have some fun with the whole thing by changing the source file:

Data:

A,B,C
100,10,100
2,20,200
3,30,150

New plots:

enter image description here

You can edit the python scripts doing the following steps:

  • Open Query Editor
  • At 'Applied steps', the first one, source, contains a small gear symbol just on the right side, click on it.

You can change the script direct into Power Query.

Related