Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
nadavsnn
Frequent Visitor

Python visual error

hi all 

I am trying to create a Python visual. when running the script on my Pycharm that uses a CSV file as that was exported from the dataset the code is working. the original code is even working on the report. 

when changing the source to the dataset  (data = dataset instead of data = pd.read_csv(r"C:\Users\*****.csv")) on the same columns in the report I get an error: 
Python script error.
KeyError: Timestamp('2021-08-03 00:00:00')

all columns are type date or string.

adding the code and the error. any help will be appreciated

 

 

 

import pandas as pd
import matplotlib.pyplot as plot
import matplotlib.pyplot as plt
color_dict = {'FV': 'yellow', 'DV': 'green', 'RTL': 'blue'}

data = dataset
data.set_index('TIME_ID')
data['TIME_ID'] = pd.to_datetime(data['TIME_ID'])
data['CALCULATED_DD_SNP'] = pd.to_datetime(data['CALCULATED_DD_SNP'])
data['PLANNED_DD_SNP'] = pd.to_datetime(data['PLANNED_DD_SNP'])
# lines = d.plot.line()

# d.plot.line(title="Milestones Over Time");
# #
# plot.show(block=True)
FV = data.loc[data['PHASE_NAME'] == 'FV']
DV = data.loc[data['PHASE_NAME'] == 'DV']
RTL = data.loc[data['PHASE_NAME'] == 'RTL']
x = data['TIME_ID']
y = data['PLANNED_DD_SNP']
plot.scatter(x, y, color='gray' ,label='Milestone')
list_of_phases = [FV, DV, RTL]
for d in list_of_phases:

    phase_name = d.iloc[0,1]

    x = d['TIME_ID']
    y = d['CALCULATED_DD_SNP']

    plot.scatter(x, y,  color=color_dict[phase_name], label=phase_name)

plot.legend()
plot.show()

 

 

 

 

 

1 ACCEPTED SOLUTION

I found out there was a bug in my code. the order of the columns in the CSV was different than the order in the dataset so this code addressed the wrong column - phase_name = d.iloc[0,1]

 

. the visual is working now. 

View solution in original post

4 REPLIES 4
v-yalanwu-msft
Community Support
Community Support

Hi, @nadavsnn ;

if it works  in pycharm. Before you can use R or Python in Power BI Desktop, you need to have the language, along with any packages you want to use, installed on your computer.
How to Use R and Python in Power BI | Power BI Languages (iterationinsights.com)


Best Regards,
Community Support Team _ Yalan Wu
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

hi, Python is installed on my PC. the original script that is addressing the CSV file is even working on the report/ I get the error when I switch to the real dataset in the report instead of the CSV file (that was exported from the real dataset). 

nadavsnn
Frequent Visitor

more error details: 

Error Message:
Python script error.
KeyError: Timestamp('2021-08-03 00:00:00')


Stack Trace:
Microsoft.PowerBI.ExploreServiceCommon.ScriptHandlerException: Python script error.
KeyError: Timestamp('2021-08-03 00:00:00')
 ---> Microsoft.PowerBI.Scripting.Python.Exceptions.PythonScriptRuntimeException: Python script error.
KeyError: Timestamp('2021-08-03 00:00:00')

   at Microsoft.PowerBI.Scripting.Python.PythonScriptWrapper.RunScript(String originalScript, Int32 timeoutMs)
   at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
   --- End of inner exception stack trace ---
   at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.RunInternal(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.Run(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.TransformDataShapeResult(QueryCommand transformCommand, SemanticQueryDataShapeCommand command, Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ExecuteDataQuery(IQueryResultDataWriter queryResultDataWriter, EngineDataModel engineDataModel, DataQuery query, Int32 queryId, ServiceErrorStatusCode& serviceErrorStatusCode, CancellationToken cancelToken)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ProcessAndWriteSemanticQueryCommands(IQueryResultsWriter queryResultsWriter, IList`1 queries, HashSet`1 pendingQueriesToCancel, EngineDataModel engineDataModel)

Invocation Stack Trace:
   at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()
   at Microsoft.Mashup.Client.UI.Shared.StackTraceInfo..ctor(String exceptionStackTrace, String invocationStackTrace, String exceptionMessage)
   at Microsoft.PowerBI.Client.Windows.ErrorHostService.GetErrorDetails(ShowErrorDialogArgs args)
   at Microsoft.PowerBI.Client.Windows.ErrorHostService.<>c__DisplayClass5_0.<ShowErrorDialogCore>b__0()
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
   at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.WindowsFormsSynchronizationContext.Send(SendOrPostCallback d, Object state)
   at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.AllowModalDialogs(Action action)
   at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.<>c__DisplayClass14_0.<ExecuteOnUIThreadAndHandlePromise>b__0()
   at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.ExecuteOnUIThreadAndHandlePromise[T](Func`1 func, IPromiseStore promiseStore, Int64 promiseHandle)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.PowerBI.Client.Windows.WebView2.WebView2Interop.InvokeCs(InteropCall call)
   at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at Microsoft.Mashup.Client.UI.Shared.WindowManager.ShowModal[T](T dialog, Func`1 showModalFunction)
   at Microsoft.PowerBI.Client.Program.<>c__DisplayClass4_1.<Main>b__3()
   at Microsoft.PowerBI.Client.Windows.IExceptionHandlerExtensions.<>c__DisplayClass3_0.<HandleExceptionsWithNestedTasks>b__0()
   at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
   at Microsoft.PowerBI.Client.Program.Main(String[] args)

I found out there was a bug in my code. the order of the columns in the CSV was different than the order in the dataset so this code addressed the wrong column - phase_name = d.iloc[0,1]

 

. the visual is working now. 

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.