Fundamentals 4 min read

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.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Sort a CSV by a Column in Descending Order with Pandas

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.

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.

Sortingdata-analysis
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.