← Back to Python Course | Chapter 13: Data Science & Web | Lesson 4 of 14

Python Pandas DataFrame

Editing Columns

Adding a new column is as simple as assigning to a new key, like df[total] = df[price] * df[qty], which computes element-wise across every row at once. Modifying an existing column works the same way, and df.drop(columns=[...]) removes columns you no longer need.

Example: Editing Columns

python
import pandas as pd
df = pd.DataFrame({"price": [10, 20], "qty": [2, 3]})
df["total"] = df["price"] * df["qty"]
print(df)

Handling Missing Data

Real-world data is rarely complete: df.isna() flags missing values, df.dropna() removes rows or columns containing them, and df.fillna(value) replaces them with a specified value or a computed statistic like the column mean. Choosing between dropping and filling depends on whether the missing data is rare enough to discard safely.

Example: Handling Missing Data

python
import pandas as pd
import numpy as np
df = pd.DataFrame({"value": [1, np.nan, 3]})
print(df.fillna(0))

Sorting DataFrames

df.sort_values(column) reorders the DataFrame's rows based on the values in one or more specified columns, ascending by default, with a ascending=False option for descending order. This is the DataFrame equivalent of Python's sorted(), but operating over full labeled rows instead of standalone values.

Example: Sorting DataFrames

python
import pandas as pd
df = pd.DataFrame({"score": [70, 90, 50]})
print(df.sort_values("score"))

Grouping Data

df.groupby(column) splits the DataFrame into groups sharing the same value in that column, and chaining an aggregation like .mean() or .sum() afterward computes that statistic separately within each group. This split-apply-combine pattern is the core tool for summarizing data by category.

Example: Grouping Data

python
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
print(df.groupby("team").mean())

Merging and Joining

pd.concat() stacks multiple DataFrames together (by rows or columns), while pd.merge() joins them based on matching values in a shared key column, similar to a SQL join. Merging is essential whenever related data is split across multiple tables that need to be combined for analysis.

Example: Merging and Joining

python
import pandas as pd
a = pd.DataFrame({"id": [1, 2], "name": ["Alex", "Sam"]})
b = pd.DataFrame({"id": [1, 2], "score": [90, 80]})
print(pd.merge(a, b, on="id"))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.