Forum Discussion

009co's avatar
009co
Icon for Helper IV rankHelper IV
4 years ago
Solved

Basic Power BI Python weirdness - getting "Python script error. KeyError: '

Very basic Power BI Python weirdness happening.

 

I create Python visual, drag two columns in values, one column is a text value and the other column is a whole number.

 

I just want to plot the text value by the whole number in simple bar chart.

 

The code is:

 

dataset = pandas.DataFrame(["Status", "Days"])
import matplotlib.pyplot as plt
dataset.plot(x="Status", y="Days", kind="bar")
 
But I am getting "Python script error. KeyError: 'Status'"
 
Any ideas what is happening?
 
 
  • 009co 

    # The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: 
    
    # dataset = pandas.DataFrame(Status, Days)
    # dataset = dataset.drop_duplicates()
    
    import matplotlib.pyplot as plt
    dataset.plot(x='Status', y='Days', kind='bar')
    plt.show()

2 Replies

  • Greg_Deckler's avatar
    Greg_Deckler
    Icon for Community Champion rankCommunity Champion

    009co 

    # The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: 
    
    # dataset = pandas.DataFrame(Status, Days)
    # dataset = dataset.drop_duplicates()
    
    import matplotlib.pyplot as plt
    dataset.plot(x='Status', y='Days', kind='bar')
    plt.show()
  • Pandas KeyError occurs when we try to access some column/row label in our DataFrame that doesn’t exist. Usually, this error occurs when you misspell a column/row name or include an unwanted space before or after the column/row name.. Before doing anything with the data frame, use print(df.columns) to see dataframe column exist or not.

     

    print(df.columns)

     

    I was getting a similar kind of error in one of my codes. Turns out, that particular index was missing from my data frame as I had dropped the empty dataframe 2 rows. If this is the case, you can do df.reset_index(inplace=True) and the error should be resolved.