Datatable to graph - KeyError: 'columnName'

Hello community,
I try to display some data from graph in the graph.
I’m using this call back:
@app.callback(
Output(‘compare’, ‘figure’),
[Input(‘exch_table’, ‘data’),
Input(‘exch_table’, ‘selected_rows’)])

def display_compare(data, rows):
fig = tools.make_subplots()
df = pd.DataFrame.from_dict(data)
select = df.ix[rows, :]
if len(rows) == 0:
trace = go.Scatter(
x=df[‘column1’], y=df[‘column2’], mode=‘markers’, showlegend=False, opacity = 0.9,
line = dict(width= 0.5, color = ‘#800000’))
else:
trace = go.Scatter(
x=select[‘column1’], y=select[‘column2’], mode=‘markers’, showlegend=False, opacity = 0.9,
line = dict(width= 0.5, color = ‘#800000’))
fig.append_trace(trace, 1, 1)

return fig   

The output is more or less fine, however the debug shows:
KeyError: ‘column1’.

What does it mean? Shall I care?

Many thanks,
Vaclav

Your function does not run completely, so you should care. The issue is that you don’t have a column in your Pandas dataframe named column1, either in df or select. Check what the df looks like to solve this issue.

He Russell,
many thanks. This was the first search I had. I’ve been searching for the clue almost two days.
I’d bet I’ve it defined, however please check this out. I’ve created a testing callback:
@app.callback(
Output(‘contain’, ‘children’),
[Input(‘exch_table’, ‘data’),
Input(‘exch_table’, ‘selected_rows’)])

def test(data, rows):
df = pd.DataFrame.from_dict(data)[0:100]

return 'You\'ve entered "{}"'.format(df['closeMean'])

And even this returns the expected values:
image

However there is the same mistake:
image

In the same time, for the same testing scenario:
return ‘You’ve entered “{}”’.format(df.columns)

The ‘closeMean’ is in the columns…
image

Very many thanks in advance.
v

Hello, once again.
@russellthehippo,
one last point: After I run the code in the Spyder IDE, there was not the issue.
Now, rerun in the console and no issue appeared.
Therefore, it seems that you don’t need to lose time.
Many thanks,
Vaclav

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.

1 Like