0Pricing
Pandas & NumPy Academy · Lektion

Nach Spaltenwerten sortieren

Sortieren Sie einen DataFrame mit sort_values() nach einer oder mehreren Spalten, steuern Sie die auf- oder absteigende Reihenfolge und legen Sie die Position von NaN fest.

Nach Spaltenwerten sortieren ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

Why Sorting Matters

Sorting a DataFrame is important for presentation (top-N reports, leaderboards), correctness (time series operations require chronological order), and performance (binary search on a sorted index is O(log n) vs O(n)). Pandas' sort_values() method is the primary tool for sorting by column content, and it returns a new DataFrame without modifying the original.

import pandas as pd

df = pd.DataFrame({
    'name': ['Dave', 'Alice', 'Carol', 'Bob'],
    'score': [75, 92, 88, 65]
})

# Sort by score descending (highest first)
ranked = df.sort_values('score', ascending=False)
print(ranked)
#     name  score
# 1  Alice     92
# 2  Carol     88
# 0   Dave     75
# 3    Bob     65

sort_values() — Basic Usage

DataFrame.sort_values(by) sorts rows by the values in the specified column. The by argument accepts a single column name (string) or a list of column names for multi-key sorting. By default, sorting is ascending (smallest first). Pass ascending=False for descending order.

import pandas as pd

df = pd.DataFrame({
    'product': ['B', 'A', 'C', 'A', 'B'],
    'price': [20, 10, 30, 15, 25]
})

# Ascending by price (default)
print(df.sort_values('price'))
#   product  price
# 1       A     10
# 3       A     15
# 0       B     20
# 4       B     25
# 2       C     30

Sorting by Multiple Columns

Passing a list of column names to sort_values(by=) sorts by the first column, then breaks ties using the second column, and so on. The ascending parameter can also be a list of booleans matching the order of the columns, allowing different sort directions for each key.

import pandas as pd

df = pd.DataFrame({
    'dept': ['HR', 'Eng', 'HR', 'Eng', 'Sales'],
    'salary': [50000, 90000, 60000, 80000, 70000],
    'name': ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
})

# Sort by dept A-Z, then by salary descending within each dept
sorted_df = df.sort_values(
    by=['dept', 'salary'],
    ascending=[True, False]
)
print(sorted_df)
#     dept  salary   name
# 1    Eng   90000    Bob
# 3    Eng   80000   Dave
# 2     HR   60000  Carol
# 0     HR   50000  Alice
# 4  Sales   70000    Eve

NaN Placement with na_position

By default, NaN values are sorted to the end of the result regardless of ascending or descending order. Use the na_position parameter to control this: 'last' (default) or 'first'. Deciding where NaN appears matters in ranked tables — missing values might represent 'unknown' and should be clearly separated from valid ranked entries.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Carol', 'Dave'],
    'score': [92, np.nan, 88, np.nan]
})

# NaN last (default)
print(df.sort_values('score', ascending=False, na_position='last'))
#     name  score
# 0  Alice   92.0
# 2  Carol   88.0
# 1    Bob    NaN
# 3   Dave    NaN

# NaN first
print(df.sort_values('score', na_position='first').head(2))

Stable Sort and kind= Parameter

Pandas uses a stable sort by default (mergesort, which is O(n log n)) — when two rows have equal values in the sort key, their original relative order is preserved. This stability matters when you sort by a primary key first, then by a secondary key: the primary sort order is maintained among ties of the secondary sort. You can change the algorithm with kind='quicksort' (faster but unstable) or kind='heapsort'.

import pandas as pd

df = pd.DataFrame({
    'group': ['A', 'B', 'A', 'B'],
    'value': [10, 10, 20, 20],
    'original_row': [0, 1, 2, 3]
})

# Stable sort: equal values keep original relative order
result = df.sort_values('value', kind='mergesort')
print(result)
#    group  value  original_row
# 0      A     10             0
# 1      B     10             1   <- row 0 before row 1 (stable)
# 2      A     20             2
# 3      B     20             3

inplace=True vs Reassignment

Like most Pandas methods, sort_values() returns a new DataFrame by default. Passing inplace=True modifies the DataFrame in place and returns None. Using inplace is generally discouraged in modern Pandas because it makes code harder to pipeline and debug — it is easier to always reassign: df = df.sort_values('col').

import pandas as pd

df = pd.DataFrame({'x': [3, 1, 4, 1, 5]})

# Preferred: reassign
df = df.sort_values('x')
print(df['x'].tolist())  # [1, 1, 3, 4, 5]

# Alternative: inplace (not recommended for pipelines)
df2 = pd.DataFrame({'x': [3, 1, 4]})
df2.sort_values('x', inplace=True)
print(df2['x'].tolist())  # [1, 3, 4]

Resetting the Index After Sorting

After sorting, the row index reflects the original positions. In a table sorted descending, row 0 might now have index 4. Call .reset_index(drop=True) to reassign sequential indices starting from 0. This is important before using .iloc[0] to get the first-ranked row reliably, or before exporting to a file where index gaps look confusing.

import pandas as pd

df = pd.DataFrame({'score': [70, 90, 80]})
sorted_df = df.sort_values('score', ascending=False)
print(sorted_df)
#    score
# 1     90
# 2     80
# 0     70

# Clean sequential index
reset_df = sorted_df.reset_index(drop=True)
print(reset_df)
#    score
# 0     90
# 1     80
# 2     70

Getting Top-N with nlargest() and nsmallest()

For selecting the top-N or bottom-N rows by a column value, df.nlargest(n, 'col') and df.nsmallest(n, 'col') are more efficient than sorting the entire DataFrame and slicing. They use a partial sort (heap selection) that is O(n log k) rather than O(n log n), which matters for large DataFrames.

import pandas as pd

df = pd.DataFrame({
    'product': ['A', 'B', 'C', 'D', 'E'],
    'revenue': [5000, 12000, 8000, 3000, 15000]
})

# Top 3 by revenue
top3 = df.nlargest(3, 'revenue')
print(top3)
#   product  revenue
# 4       E    15000
# 1       B    12000
# 2       C     8000

# Bottom 2 by revenue
bottom2 = df.nsmallest(2, 'revenue')
print(bottom2)

Sorting Categorical Columns by Category Order

When sorting a column that contains an ordered Categorical dtype, sort_values() respects the category order rather than alphabetical order. This is essential for correctly ordering priority levels, severity ratings, or size labels — 'Small' should come before 'Medium' before 'Large', not in alphabetical order where 'Large' comes first.

import pandas as pd

df = pd.DataFrame({
    'size': pd.Categorical(
        ['Large', 'Small', 'Medium', 'Small', 'Large'],
        categories=['Small', 'Medium', 'Large'],
        ordered=True
    ),
    'count': [10, 5, 8, 3, 7]
})

print(df.sort_values('size'))
#      size  count
# 1   Small      5
# 3   Small      3
# 2  Medium      8
# 0   Large     10
# 4   Large      7

Chaining Sort with Other Operations

Because sort_values() returns a DataFrame, it integrates naturally into method chains. A typical pattern is: filter rows → aggregate → sort → display top-N. Chaining keeps the transformation pipeline linear and readable.

import pandas as pd

df = pd.DataFrame({
    'dept': ['Eng', 'HR', 'Eng', 'Sales', 'HR', 'Eng'],
    'salary': [90000, 50000, 120000, 70000, 55000, 80000]
})

result = (
    df
    .groupby('dept')['salary'].mean()
    .reset_index()
    .sort_values('salary', ascending=False)
    .head(2)
)
print(result)
#    dept    salary
# 0   Eng  96666.67
# 2  Sales  70000.00

Practical: Top-5 Products Report

Here is a practical end-to-end example of producing a top-5 products report by revenue: load data, compute total revenue per product, sort descending, take the top 5, reset the index to produce a clean rank number, and add a rank column for display.

import pandas as pd

orders = pd.DataFrame({
    'product': ['A', 'B', 'A', 'C', 'B', 'D', 'E', 'A', 'C', 'E'],
    'revenue': [100, 200, 150, 80, 300, 60, 400, 120, 90, 350]
})

top5 = (
    orders
    .groupby('product')['revenue'].sum()
    .reset_index()
    .sort_values('revenue', ascending=False)
    .head(5)
    .reset_index(drop=True)
)
top5.index = top5.index + 1  # rank from 1
top5.index.name = 'rank'
print(top5)

Quick Check

Test your understanding of sorting DataFrames by column values.

Lesson Recap

In this lesson you learned: sort_values(by=) sorts by one or more columns, ascending= can be a list for different directions per key, na_position='last' controls NaN placement, and nlargest()/nsmallest() efficiently extract the top/bottom N rows without sorting the entire DataFrame. Always reset_index() after sorting for clean sequential output. Next up we sort by the DataFrame index.

Häufig gestellte Fragen

Ist die Lektion „Nach Spaltenwerten sortieren“ kostenlos?

Ja — der vollständige Text von „Nach Spaltenwerten sortieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Nach Spaltenwerten sortieren“?

Sortieren Sie einen DataFrame mit sort_values() nach einer oder mehreren Spalten, steuern Sie die auf- oder absteigende Reihenfolge und legen Sie die Position von NaN fest. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?

Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.

Wie lange dauert die Lektion „Nach Spaltenwerten sortieren“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?

Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Nach Spaltenwerten sortieren
  2. Nach dem Index sortieren
  3. Werte rangordnen
  4. Index setzen und zurücksetzen
← Zurück zu Pandas & NumPy Academy