0

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()

1 Answer 1

1
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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.