Pandas
Analyze, clean, combine, reshape, and export tabular data with pandas 3.
Other Python Sheets
Setup and Core Structures
Install pandas and create its primary data structures.
Install pandas and inspect the active version.
python -m pip install pandas
import pandas as pdCreate a labeled one-dimensional array.
scores = pd.Series([88, 92, 79], name="score")Create a labeled two-dimensional table.
df = pd.DataFrame({
"name": ["Ana", "Ben"],
"score": [88, 92],
})Inspect Data
Understand shape, columns, types, and distributions.
Inspect rows and structural metadata.
df.head()
df.tail()
df.shapeSummarize numeric and categorical columns.
df.describe()Select Rows and Columns
Select data by label, position, or scalar location.
Select one or multiple columns and row slices.
names = df["name"]
subset = df[["name", "score"]]Select by labels or integer positions.
df.loc["ana", "score"]
df.iloc[0, 1]Filter and Query
Keep rows that match one or more conditions.
Filter rows with vectorized conditions.
high = df[df["score"] >= 90]Filter with a readable expression string.
minimum = 90
high = df.query("score >= @minimum")Assign and Index
Update values safely under pandas 3 Copy-on-Write.
Assign in one step with loc.
df.loc[df["score"] < 80, "status"] = "review"Set meaningful row labels and hierarchical indexes.
df = df.set_index("id")
df = df.reset_index()Missing and Duplicate Data
Detect, fill, remove, and deduplicate imperfect data.
Find and handle missing values by column.
df.isna().sum()
df = df.dropna(subset=["id"])Detect and remove repeated records.
df.duplicated().sum()
df = df.drop_duplicates()Data Types
Inspect and convert columns to suitable pandas dtypes.
Convert columns with explicit error handling.
df["score"] = pd.to_numeric(df["score"], errors="coerce")Use the default dedicated string dtype safely.
names = pd.Series(["Ana", "Ben", None], dtype="str")Text and Categories
Transform strings and optimize repeated labels.
Clean and extract text without Python loops.
df["name"] = df["name"].str.strip().str.title()Represent repeated finite labels efficiently.
df["size"] = df["size"].astype("category")Dates and Time
Parse, extract, group, and shift time-based data.
Parse timestamps and use the dt accessor.
df["created_at"] = pd.to_datetime(df["created_at"], utc=True)Calculate durations and compare adjacent rows.
df["duration"] = df["ended_at"] - df["started_at"]Operations and Sorting
Apply vectorized calculations and order results.
Calculate with columns and align by labels.
df["total"] = df["price"] * df["quantity"]Sort rows or control column order.
df = df.sort_values("score", ascending=False)Group and Aggregate
Split data into groups and calculate summaries.
Calculate one or more summaries per group.
summary = df.groupby("team")["score"].mean()Return group-aligned values or remove whole groups.
df["team_avg"] = df.groupby("team")["score"].transform("mean")Combine Data
Join related tables and concatenate compatible objects.
Combine tables using matching key columns.
result = orders.merge(customers, on="customer_id", how="left")Stack rows or align objects by columns.
all_rows = pd.concat([january, february], ignore_index=True)Reshape Data
Convert between wide, long, nested, and summary forms.
Reshape long data to wide form and back.
wide = df.pivot(index="date", columns="metric", values="value")Expand list values and flatten nested records.
rows = df.explode("tags", ignore_index=True)Windows and Time Series
Calculate rolling, expanding, and indexed time metrics.
Calculate statistics across moving or cumulative windows.
df["moving_avg"] = df["value"].rolling(7, min_periods=1).mean()Import and Export
Read and write common tabular storage formats.
Load and save common text and spreadsheet formats.
df = pd.read_csv("input.csv")
df.to_csv("output.csv", index=False)Use efficient storage and process large inputs.
df.to_parquet("data.parquet", index=False)
df = pd.read_parquet("data.parquet")Plotting and Performance
Visualize results and keep transformations efficient.
Create exploratory plots from Series and DataFrames.
df.plot(x="date", y="value", kind="line")Write predictable pandas 3 transformations.
df.loc[df["score"] < 0, "score"] = 0