Reputation: 111
I am unable to apply a custom function to a data frame without receiving the error message "KeyError: 'state'". See code below.
import plotly.express as px
df = pd.DataFrame({'state':['IL', 'MN', "MN"]})
state_ct = (df
.groupby(['state'])['state']
.size()
.reset_index(name='count'))
def heat_map(df):
fig = px.choropleth(df,
locations=df['state'],
locationmode='USA-states',
scope='usa',
color='count',
color_continuous_scale='reds')
return(fig.show())
state_ct.apply(heat_map)
However, I can run the plotly code outside of the function with the state_ct data frame and have no issues. What is causing the issue when trying to run this through the custom Python function?
fig = px.choropleth(state_ct,
locations=state_ct['state'],
locationmode='USA-states',
scope='usa',
color='count',
color_continuous_scale='reds')
fig.show()
Upvotes: 0
Views: 1289
Reputation: 31226
apply()
returns a dataframe or series. Your function returns a plotly figure.import plotly.express as px
df = pd.DataFrame({'state':['IL', 'MN', "MN"]})
state_ct = (df
.groupby(['state'])['state']
.size()
.reset_index(name='count'))
def heat_map(df):
fig = px.choropleth(df,
locations=df['state'],
locationmode='USA-states',
scope='usa',
color='count',
color_continuous_scale='reds')
return(fig.show())
heat_map(state_ct)
Upvotes: 1