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
Create a New Dataframe Based on Rows With a Certain Value
Pandas - Replace Outliers With Groupby Mean
Python Key Error=0 - Can't Find Dict Error in Code
Plotting Categorical Data With Pandas and Matplotlib
Access Is Denied When Trying to Pip Install a Package on Windows
How to Print the Even-Indexed and Odd-Indexed Characters of Strings
Drop Non-Numeric Columns from a Pandas Dataframe
Calculate the Lcm of a List of Given Numbers in Python
Pandas Groupby Columns With Nan (Missing) Values
Python Converting MySQL Query Result to Json
Python - Ensuring a Variable Holds a Positive Number
Reading a CSV That Sometimes Contain Multiple Whitespaces
How to Set Proxy for Chrome in Python Webdriver
Clearing All Labels from a Tkinter Window
How to Remove Additional Commas in a List in Python
How to Cleanly Uninstall Ansible
How to Assign Values to a Numpy Array as a Function of Index