Skip to content
Advertisement

unboundlocalerror while using datetime to create new dataframe

I keep getting an error

JavaScript

for this function:

JavaScript

This isn’t the full function, but the whole problem lies here. I am trying to create a new dataframe that only pulls from the past year of the initial dataframe.

I will need to create options for year count using a function variable once I get this figured out, but for right now I’m already getting an error here.

If I do this ‘df’ line outside the function, it works fine unto itself so.. must be something about calling it within the function.

Advertisement

Answer

This is happening because you’re using the same name for the new variable as the one you already have, df. This is making the python interpreter think that you’re trying to reference df in it’s own creation, so you’re “referencing” the variable before it’s assignment, like the error message says.

JavaScript

There are a couple ways to fix this. You could indicate that the variable you’re using is global.

JavaScript

As you can see, this does have the side effect of actually mutating that global variable. Which may or may not be what you’re after.

You could also just use a different name.

JavaScript
Advertisement