A NameError usually happens when Python cannot find the variable or column name you referenced.
When sorting a pandas DataFrame, this often occurs if the column name is written without quotes or if the variable does not exist in the current scope.
For example, this will cause a NameError:
df.sort_values(by=column_name)
if column_name is not defined.
Instead, reference the column as a string:
df.sort_values(by="column_name")
Also ensure that:
-
The DataFrame (
df) exists -
The column name is spelled correctly
-
The column actually exists in
df.columns
Checking df.columns before sorting can help confirm the correct column name.

Be the first to post a comment.