Fundamentals 3 min read

How to Sort a CSV by a Specific Column in Descending Order Using Python pandas

This article shows how to read a CSV file with pandas, sort its rows by a chosen column in descending order while preserving the header, and save the sorted data to a new CSV, providing a clear, step‑by‑step solution for Python automation tasks.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Sort a CSV by a Specific Column in Descending Order Using Python pandas

A user asked how to sort a CSV file by a specific column while keeping the header unchanged.

Solution

The following pandas code reads the CSV, sorts by the "总价" column in descending order, resets the index, and saves the result to a new file.

import pandas as pd
# Adjust encoding as needed
df = pd.read_csv("test.csv", encoding="gbk")
print(df.head())
# Sort by "总价" column descending
df = df.sort_values(by=["总价"], ascending=[False], ignore_index=True)
print(df.head())
# Save to new CSV without the index
df.to_csv("test2.csv", index=False)

Additional notes: df.sort_values(col2, ascending=False) sorts by a single column, while df.sort_values([col1, col2], ascending=[True, False]) allows multi‑column sorting with different orders.

Summary

The article demonstrates a straightforward pandas approach to reorder CSV rows based on a chosen column, providing a practical example that can be directly applied to similar automation tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAutomationCSVpandasdata sorting
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.