A NameError typically occurs when Python cannot find the variable you referenced.
When sorting a pandas DataFrame, this often happens if the column name is written without quotes, making Python treat it as a variable instead of a string.
Example that causes the error:
df.sort_values(by=column_name)
If column_name is not defined, Python raises a NameError.
The correct approach is:
df.sort_values(by="column_name")
Also make sure the column actually exists in the DataFrame. You can verify this with:
print(df.columns)

Be the first to post a comment.