pandas Cheatsheet

Series and DataFrame

Use this pandas reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

Setup and Core Objects

import pandas as pd
import numpy as np

pd.__version__                    # check installed version

# Display options
pd.set_option("display.max_columns", None)
pd.set_option("display.max_rows", 100)
pd.set_option("display.float_format", "{:.2f}".format)
ObjectDescription
Series1-D labeled array: values + index
DataFrame2-D labeled table: columns of Series sharing a row index
IndexImmutable axis labels (rows or columns)

Creating a Series

import pandas as pd
import numpy as np

# From list
s = pd.Series([10, 20, 30])

# From list with custom index
s = pd.Series([10, 20, 30], index=["a", "b", "c"])

# From dict (keys become index)
s = pd.Series({"a": 10, "b": 20, "c": 30})

# From scalar (broadcast)
s = pd.Series(5, index=["a", "b", "c"])

# With name
s = pd.Series([1, 2, 3], name="score")

Series Attributes

AttributeDescription
s.valuesUnderlying NumPy array (or ExtensionArray)
s.indexIndex object
s.dtypeData type
s.nameSeries name
s.shapeTuple (n,)
s.sizeTotal number of elements
s.nbytesMemory usage in bytes
s.is_monotonic_increasingTrue if values are monotonically increasing

Creating a DataFrame

# From dict of lists (keys = column names)
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})

# From list of dicts (each dict = one row)
df = pd.DataFrame([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}])

# From 2-D NumPy array
df = pd.DataFrame(np.arange(12).reshape(3, 4), columns=["a", "b", "c", "d"])

# From another DataFrame (copy)
df2 = pd.DataFrame(df)

# With explicit index
df = pd.DataFrame({"x": [1, 2, 3]}, index=["r1", "r2", "r3"])

# Empty DataFrame with schema
df = pd.DataFrame(columns=["id", "value"], dtype=float)

DataFrame Attributes

AttributeDescription
df.shape(rows, cols)
df.dtypesPer-column dtype Series
df.columnsColumn Index
df.indexRow Index
df.valuesUnderlying 2-D NumPy array
df.sizeTotal element count
df.ndimAlways 2
df.emptyTrue if any axis is length 0
df.axesList [row_index, col_index]
df.memory_usage(deep=True)Bytes per column

Inspecting a DataFrame

df.head(5)         # first N rows (default 5)
df.tail(5)         # last N rows
df.sample(10)      # random N rows
df.info()          # column dtypes + non-null counts
df.describe()      # stats for numeric cols
df.describe(include="all")  # stats for all cols
df.nunique()       # unique value count per column
df.value_counts()  # (on Series) frequency table

Index Operations

# Reset index (moves index to a column)
df.reset_index()
df.reset_index(drop=True)     # discard old index

# Set a column as index
df.set_index("name")
df.set_index(["year", "month"])   # MultiIndex

# Rename index
df.index.rename("row_id", inplace=True)

# Re-index to new label set (introduces NaN for missing)
df.reindex([0, 1, 2, 99])

# Sort by index
df.sort_index()
df.sort_index(ascending=False)

Copying and Casting

df_copy = df.copy()             # deep copy (default)
df_copy = df.copy(deep=False)   # shallow copy

# Cast a column
df["age"] = df["age"].astype(int)
df = df.astype({"age": int, "score": float})

# Convert Series dtype
s = s.astype("category")
s = s.astype("string")   # pd.StringDtype (nullable)

Converting Between Series and DataFrame

# Series → single-column DataFrame
s.to_frame()
s.to_frame(name="value")

# Single-column DataFrame → Series
df["col"].squeeze()

# DataFrame column as Series
s = df["col"]           # Copy-on-Write (default in 3.0): behaves as a copy — writing to s never mutates df
s = df["col"].copy()    # explicit independent copy

Common Constructor Patterns

# Range index (implicit, 0-based)
df = pd.DataFrame({"a": range(5)})

# DatetimeIndex as row index
dates = pd.date_range("2024-01-01", periods=5, freq="D")
df = pd.DataFrame({"v": range(5)}, index=dates)

# MultiIndex DataFrame
arrays = [["A", "A", "B", "B"], [1, 2, 1, 2]]
idx = pd.MultiIndex.from_arrays(arrays, names=["letter", "number"])
df = pd.DataFrame({"val": [10, 20, 30, 40]}, index=idx)