Jupyter Notebook Python Nameerror

Name error when calling defined function in Jupyter

Your function definition isn't getting executed by the Python interpreter before you call the function.

Double check what is getting executed and when. In Jupyter it's possible to run code out of input-order, which seems to be what you are accidentally doing. (perhaps try 'Run All')

"NameError: name 'Counter' is not defined" on Jupyter Notebook but works fine on PyCharm?

In your notebook cell 14:

def return_counter(data_frame, column_name, limit):
from collections import Counter
print(dict(Counter(data_frame[column_name].values).most_common(limit)))

you import the Counter class in the scope of the return_counter function (at function scope). By doing that, the name Counter is only defined for code that appears later in that function's body. Then in that same cell, because the third line is indented at the same level as the function definition, you are attempting to instantiate the Counter class at global (notebook) scope. The name Counter is not defined at that point in the global scope, and so you get the error you're seeing.

To fix this, either move the offending line inside the function:

def return_counter(data_frame, column_name, limit):
from collections import Counter
print(dict(Counter(data_frame[column_name].values).most_common(limit)))

or import the Counter object at global scope

def return_counter(data_frame, column_name, limit):
from collections import Counter
from collections import Counter
print(dict(Counter(data_frame[column_name].values).most_common(limit)))

As you have it, your return_counter function does nothing and has no reason to import the Counter class, so I assume it is the first option that you were going for.



Related Topics



Leave a reply



Submit