Sort a CSV by a Column in Descending Order with Pandas
This article demonstrates how to keep a CSV file's header unchanged while sorting its rows in descending order based on a specific column using Python's pandas library, providing step‑by‑step code, explanations, and sample output to help readers automate data processing tasks.
1. Introduction
A user asked how to sort a CSV file while preserving the header row, arranging the data by the fourth column in descending order and saving the result as a new CSV file.
2. Solution Process
The following straightforward Pandas approach solves the problem.
import pandas as pd
# Set the appropriate encoding for your file
df = pd.read_csv("test.csv", encoding="gbk")
print(df.head())
# Sort by the "总价" column in descending order and reset the index
df = df.sort_values(by=["总价"], ascending=[False], ignore_index=True)
print(df.head())
# Save to a new file without writing the index
df.to_csv("test2.csv", index=False)For multiple‑column sorting you can pass a list of column names to by and a corresponding list of booleans to ascending, e.g., df.sort_values([col1, col2], ascending=[True, False]).
3. Summary
The provided code reads the original CSV, sorts it by the specified column in descending order while keeping the header unchanged, and writes the sorted data to a new CSV file. This method offers a quick, reproducible solution for common data‑processing tasks in Python.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
