Why do I get a NameError when sorting a pandas DataFrame column?

Oscar
Updated on February 24, 2026 in

I am working with a pandas DataFrame and trying to sort a numeric column (trip_distance) in descending order.

However, I receive a NameError: name 'trip_distance' is not defined when using:

trip = sorted(trip_distance)
print(trip)

The column exists inside my DataFrame (e.g., df).

I would like clarity on:

  • Why this NameError occurs

  • The correct way to sort a DataFrame column in descending order

  • When to use sorted() versus DataFrame.sort_values()

Any guidance on best practices for sorting columns in pandas would be appreciated.

  • 2
  • 106
  • 2 months ago
 
on March 10, 2026

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)
  • Liked by
Reply
Cancel
on March 10, 2026

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.

  • Liked by
Reply
Cancel
Loading more replies