10 Minutes to pandas

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page is a quick, practical tour of pandas 3.1 for readers who know some Python and want to get productive fast. It follows the order of the official "10 minutes to pandas" guide (create, view, select, set, handle missing data, operate, combine, group, reshape, work with time, categoricals, plot, read and write), but every snippet was rewritten with deterministic data and run on Python 3.13 with pandas 3.1.0 and NumPy 2.5.4; the output shown is real. It was checked in October 2026. Install pandas first if you have not (Installing pandas and Understanding Its Versions); each topic below has a dedicated page that goes much deeper, linked at the end of its section.

Three differences from tutorials written before 2026 appear on almost every screen, so keep them in mind:

  • Strings are a dedicated str dtype, not object: a column of text prints dtype: str, and so do column labels made of strings (Index([...], dtype='str')).

  • Datetimes default to microsecond resolution (datetime64[us]), no longer nanoseconds.

  • Copy-on-Write is the only mode. A subset never writes through to its parent, so chained assignment such as df["a"][mask] = 1 does nothing (it emits a ChainedAssignmentError warning).

The snippets share state: run them top to bottom in one session, starting with the imports below.

flowchart LR A[Create] --> B[View] B --> C[Select] C --> D[Clean] D --> E[Transform and group] E --> F[Combine] F --> G[Reshape] G --> H[Export]

Object creation

pandas has two workhorse structures: a Series (one labelled column of one dtype) and a DataFrame (a table of Series sharing one row index). A Series made from a list takes a default RangeIndex, and np.nan makes the dtype float64:

import numpy as np
import pandas as pd

s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
print(s.dtype)
0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64
float64

A DataFrame from a NumPy array needs an index and column labels; date_range builds a datetime index:

rng = np.random.default_rng(42)
dates = pd.date_range("2013-01-01", periods=6)
df = pd.DataFrame(rng.standard_normal((6, 4)).round(2), index=dates, columns=list("ABCD"))
print(df)
print(dates.dtype)
               A     B     C     D
2013-01-01  0.30 -1.04  0.75  0.94
2013-01-02 -1.95 -1.30  0.13 -0.32
2013-01-03 -0.02 -0.85  0.88  0.78
2013-01-04  0.07  1.13  0.47 -0.86
2013-01-05  0.37 -0.96  0.88 -0.05
2013-01-06 -0.18 -0.68  1.22 -0.15
datetime64[us]

A dictionary of columns gives each column its own dtype, and scalars are broadcast to the length of the others:

df2 = pd.DataFrame({
    "A": 1.0,
    "B": pd.Timestamp("2013-01-02"),
    "C": pd.Series(1, index=list(range(4)), dtype="float32"),
    "D": np.array([3] * 4, dtype="int32"),
    "E": pd.Categorical(["test", "train", "test", "train"]),
    "F": "foo",
})
print(df2)
print(df2.dtypes)
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo
A           float64
B    datetime64[us]
C           float32
D             int32
E          category
F               str
dtype: object

Note the last line of the dtypes: column F is str, where code written for pandas 2 would show object.

Viewing data

head and tail show the first and last rows (five by default), index and columns show the labels, and describe summarises the numeric columns:

print(df.head(2))
print(df.index)
print(df.columns)
print(df.describe().round(2))
               A     B     C     D
2013-01-01  0.30 -1.04  0.75  0.94
2013-01-02 -1.95 -1.30  0.13 -0.32
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[us]', freq='D')
Index(['A', 'B', 'C', 'D'], dtype='str')
          A     B     C     D
count  6.00  6.00  6.00  6.00
mean  -0.24 -0.62  0.72  0.06
std    0.86  0.88  0.38  0.68
min   -1.95 -1.30  0.13 -0.86
25%   -0.14 -1.02  0.54 -0.28
50%    0.02 -0.90  0.82 -0.10
75%    0.24 -0.72  0.88  0.57
max    0.37  1.13  1.22  0.94

to_numpy() returns the data as a NumPy array. Because of Copy-on-Write the array can be a read-only view of the frame’s memory, so copy it (df.to_numpy().copy()) before modifying it:

arr = df.to_numpy()
print(arr.dtype, arr.flags.writeable)   # float64 False

Sorting is by label (sort_index) or by value (sort_values); both return a new object:

print(df.sort_index(axis=1, ascending=False).head(2))
print(df.sort_values(by="B").head(3))
               D     C     B     A
2013-01-01  0.94  0.75 -1.04  0.30
2013-01-02 -0.32  0.13 -1.30 -1.95
               A     B     C     D
2013-01-02 -1.95 -1.30  0.13 -0.32
2013-01-01  0.30 -1.04  0.75  0.94
2013-01-05  0.37 -0.96  0.88 -0.05

Selection

There are four selectors worth learning by heart: [] for a column or a row slice, .loc for labels (slice ends are inclusive), .iloc for positions (slice ends are exclusive, like Python), and .at and .iat for a single value.

print(df["A"].head(2))                          # one column -> Series
print(df[0:3])                                  # row slice by position
print(df["2013-01-02":"2013-01-04"])            # row slice by label, end included
print(df.loc[dates[0]])                         # one row by label -> Series
print(df.loc["2013-01-02":"2013-01-04", ["A", "B"]])
print(df.loc[dates[0], "A"], df.at[dates[0], "A"])
print(df.iloc[3:5, 0:2])                        # positions, end excluded
print(df.iloc[[1, 2, 4], [0, 2]])
print(df.iat[1, 1])
2013-01-01    0.30
2013-01-02   -1.95
Freq: D, Name: A, dtype: float64
               A     B     C     D
2013-01-01  0.30 -1.04  0.75  0.94
2013-01-02 -1.95 -1.30  0.13 -0.32
2013-01-03 -0.02 -0.85  0.88  0.78
               A     B     C     D
2013-01-02 -1.95 -1.30  0.13 -0.32
2013-01-03 -0.02 -0.85  0.88  0.78
2013-01-04  0.07  1.13  0.47 -0.86
A    0.30
B   -1.04
C    0.75
D    0.94
Name: 2013-01-01 00:00:00, dtype: float64
               A     B
2013-01-02 -1.95 -1.30
2013-01-03 -0.02 -0.85
2013-01-04  0.07  1.13
0.3 0.3
               A     B
2013-01-04  0.07  1.13
2013-01-05  0.37 -0.96
               A     C
2013-01-02 -1.95  0.13
2013-01-03 -0.02  0.88
2013-01-05  0.37  0.88
-1.3

A boolean mask keeps the rows where a condition holds, a frame-wide condition keeps the shape and puts NaN where it fails, and isin tests membership:

print(df[df["A"] > 0])
print(df[df > 0])

df2 = df.copy()
df2["E"] = ["one", "one", "two", "three", "four", "three"]
print(df2[df2["E"].isin(["two", "four"])])
               A     B     C     D
2013-01-01  0.30 -1.04  0.75  0.94
2013-01-04  0.07  1.13  0.47 -0.86
2013-01-05  0.37 -0.96  0.88 -0.05
               A     B     C     D
2013-01-01  0.30   NaN  0.75  0.94
2013-01-02   NaN   NaN  0.13   NaN
2013-01-03   NaN   NaN  0.88  0.78
2013-01-04  0.07  1.13  0.47   NaN
2013-01-05  0.37   NaN  0.88   NaN
2013-01-06   NaN   NaN  1.22   NaN
               A     B     C     D     E
2013-01-03 -0.02 -0.85  0.88  0.78   two
2013-01-05  0.37 -0.96  0.88 -0.05  four

pandas 3 also lets you write conditions and calculations with column expressions: pd.col("a") stands for "the column a of whatever frame this is applied to", so it works inside assign, loc and method chains without a temporary variable. Since 3.1 the frame also has a select method:

d = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(d.assign(c=pd.col("a") + pd.col("b")))
print(d.loc[pd.col("a") > 1])
print(d.select("a"))
   a   b   c
0  1  10  11
1  2  20  22
2  3  30  33
   a   b
1  2  20
2  3  30
   a
0  1
1  2
2  3

Setting values

Assign a new column from a Series and pandas aligns it on the index (rows without a partner become NaN); assign single values with .at and .iat, and whole columns with .loc:

s1 = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range("2013-01-02", periods=6))
df["F"] = s1                                   # aligned on the index
df.at[dates[0], "A"] = 0                       # by label
df.iat[0, 1] = 0                               # by position
df.loc[:, "D"] = np.array([5] * len(df))       # a whole column
print(df)

df3 = df.copy()
df3[df3 > 0] = -df3                            # where positive, flip the sign
print(df3)
               A     B     C    D    F
2013-01-01  0.00  0.00  0.75  5.0  NaN
2013-01-02 -1.95 -1.30  0.13  5.0  1.0
2013-01-03 -0.02 -0.85  0.88  5.0  2.0
2013-01-04  0.07  1.13  0.47  5.0  3.0
2013-01-05  0.37 -0.96  0.88  5.0  4.0
2013-01-06 -0.18 -0.68  1.22  5.0  5.0
               A     B     C    D    F
2013-01-01  0.00  0.00 -0.75 -5.0  NaN
2013-01-02 -1.95 -1.30 -0.13 -5.0 -1.0
2013-01-03 -0.02 -0.85 -0.88 -5.0 -2.0
2013-01-04 -0.07 -1.13 -0.47 -5.0 -3.0
2013-01-05 -0.37 -0.96 -0.88 -5.0 -4.0
2013-01-06 -0.18 -0.68 -1.22 -5.0 -5.0

The classic mistake is chained assignment: indexing twice and assigning to the intermediate result. With Copy-on-Write the intermediate object is a copy, so the original is never modified, and pandas 3 warns you:

import warnings

d = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    d["a"][d["b"] > 4] = 99                    # does nothing
print(d.to_dict("list"), [type(w.message).__name__ for w in caught])

d.loc[d["b"] > 4, "a"] = 99                    # one indexing operation: works
print(d.to_dict("list"))
{'a': [1, 2, 3], 'b': [4, 5, 6]} ['ChainedAssignmentError']
{'a': [1, 99, 99], 'b': [4, 5, 6]}

SettingWithCopyWarning no longer exists; ChainedAssignmentError is a warning, not an exception. Always select rows and columns in one .loc call when assigning. Assigning a float into an integer column also no longer silently upcasts (PDEP-6): it raises, so convert the column first with astype.

Missing data

pandas uses NaN (and NaT for datetimes) to represent missing values. reindex creates or changes the row and column labels and is a convenient way to produce gaps. dropna removes rows with missing values, fillna replaces them and pd.isna returns a boolean mask:

df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ["E"])
df1.loc[dates[0]:dates[1], "E"] = 1
print(df1)
print(df1.dropna(how="any"))
print(df1.fillna(value=5))
print(pd.isna(df1))
               A     B     C    D    F    E
2013-01-01  0.00  0.00  0.75  5.0  NaN  1.0
2013-01-02 -1.95 -1.30  0.13  5.0  1.0  1.0
2013-01-03 -0.02 -0.85  0.88  5.0  2.0  NaN
2013-01-04  0.07  1.13  0.47  5.0  3.0  NaN
               A    B     C    D    F    E
2013-01-02 -1.95 -1.3  0.13  5.0  1.0  1.0
               A     B     C    D    F    E
2013-01-01  0.00  0.00  0.75  5.0  5.0  1.0
2013-01-02 -1.95 -1.30  0.13  5.0  1.0  1.0
2013-01-03 -0.02 -0.85  0.88  5.0  2.0  5.0
2013-01-04  0.07  1.13  0.47  5.0  3.0  5.0
                A      B      C      D      F      E
2013-01-01  False  False  False  False   True  False
2013-01-02  False  False  False  False  False  False
2013-01-03  False  False  False  False  False   True
2013-01-04  False  False  False  False  False   True

Use ffill() and bfill() to propagate neighbouring values; the old fillna(method="ffill") form was removed in pandas 3.0.

Operations

Statistics skip missing values by default and work along an axis (axis=0 collapses rows, giving one value per column; axis=1 gives one value per row). Arithmetic between objects aligns on labels first and puts NaN where a label has no partner:

df = pd.DataFrame(np.random.default_rng(42).standard_normal((6, 4)).round(2),
                  index=dates, columns=list("ABCD"))
df["F"] = pd.Series([1, 2, 3, 4, 5, 6], index=dates)

print(df.mean().round(2))                       # per column
print(df.mean(axis=1).round(2))                 # per row

s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
print(s)
print(df.sub(s, axis="index").round(2))
A   -0.24
B   -0.62
C    0.72
D    0.06
F    3.50
dtype: float64
2013-01-01    0.39
2013-01-02   -0.29
2013-01-03    0.76
2013-01-04    0.96
2013-01-05    1.05
2013-01-06    1.24
Freq: D, dtype: float64
2013-01-01    NaN
2013-01-02    NaN
2013-01-03    1.0
2013-01-04    3.0
2013-01-05    5.0
2013-01-06    NaN
Freq: D, dtype: float64
               A     B     C     D    F
2013-01-01   NaN   NaN   NaN   NaN  NaN
2013-01-02   NaN   NaN   NaN   NaN  NaN
2013-01-03 -1.02 -1.85 -0.12 -0.22  2.0
2013-01-04 -2.93 -1.87 -2.53 -3.86  1.0
2013-01-05 -4.63 -5.96 -4.12 -5.05  0.0
2013-01-06   NaN   NaN   NaN   NaN  NaN

agg applies one or several reductions, transform returns a result of the same shape (here, centring each column), value_counts counts distinct values and the .str accessor applies string methods to a text column:

print(df.agg(["min", "max"]).round(2))
print(df.transform(lambda x: x - x.mean()).round(2).head(3))
print(pd.Series([3, 1, 3, 2, 3, 1]).value_counts())

names = pd.Series(["A", "Baca", np.nan, "CABA", "dog"])
print(names.str.lower())
print(names.dtype)
        A     B     C     D  F
min -1.95 -1.30  0.13 -0.86  1
max  0.37  1.13  1.22  0.94  6
               A     B     C     D    F
2013-01-01  0.53 -0.42  0.03  0.88 -2.5
2013-01-02 -1.72 -0.68 -0.59 -0.38 -1.5
2013-01-03  0.22 -0.23  0.16  0.72 -0.5
3    3
1    2
2    1
Name: count, dtype: int64
0       a
1    baca
2     NaN
3    caba
4     dog
dtype: str
str

Two removals matter here: DataFrame.applymap is gone (use DataFrame.map for an element-wise function) and the top-level pd.value_counts was removed in 3.0 (call the method on the Series).

Concat and merge

pd.concat glues objects together along an axis. Never grow a DataFrame row by row: DataFrame.append was removed in pandas 2.0 and repeated concatenation is quadratic. Collect pieces in a list and call concat once. pd.merge joins on columns, like a SQL join:

pieces = [df.iloc[:3], df.iloc[3:5], df.iloc[5:]]
print(pd.concat(pieces).shape)                 # (6, 5): the pieces are stacked back together

left = pd.DataFrame({"key": ["foo", "bar"], "lval": [1, 2]})
right = pd.DataFrame({"key": ["foo", "bar"], "rval": [4, 5]})
print(pd.merge(left, right, on="key"))

# duplicate keys multiply: every left row pairs with every right row of the same key
left = pd.DataFrame({"key": ["foo", "foo"], "lval": [1, 2]})
right = pd.DataFrame({"key": ["foo", "foo"], "rval": [4, 5]})
print(pd.merge(left, right, on="key"))

# anti-join (pandas 3.0): rows of the left frame without a partner on the right
customers = pd.DataFrame({"key": ["a", "b", "c"], "v": [1, 2, 3]})
orders = pd.DataFrame({"key": ["a", "b"]})
print(pd.merge(customers, orders, on="key", how="left_anti"))
(6, 5)
   key  lval  rval
0  foo     1     4
1  bar     2     5
   key  lval  rval
0  foo     1     4
1  foo     1     5
2  foo     2     4
3  foo     2     5
  key  v
2   c  3

Grouping

Group by means splitting the data into groups, applying a function to each and combining the results. The grouped columns become the index of the result; selecting the columns to aggregate explicitly keeps the code stable when the frame has text columns:

g = pd.DataFrame({
    "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
    "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
    "C": [1.5, 2.0, 0.5, 1.0, 2.5, 3.0, 1.0, 0.5],
    "D": [10, 20, 30, 40, 50, 60, 70, 80],
})
print(g.groupby("A")[["C", "D"]].sum())
print(g.groupby(["A", "B"])[["C", "D"]].sum())
print(g.groupby("A").agg(total_c=("C", "sum"), mean_d=("D", "mean"), n=("D", "size")))
       C    D
A
bar  6.0  120
foo  6.0  240
             C   D
A   B
bar one    2.0  20
    three  1.0  40
    two    3.0  60
foo one    2.5  80
    three  0.5  80
    two    3.0  80
     total_c  mean_d  n
A
bar      6.0    40.0  3
foo      6.0    48.0  5

The last form is named aggregation: new_name=("column", "function"). It produces flat, readable column names.

Reshaping

stack moves column labels into the row index (long format) and unstack does the reverse; pivot_table summarises one column over two keys:

index = pd.MultiIndex.from_product([["bar", "baz"], ["one", "two"]], names=["first", "second"])
df2 = pd.DataFrame({"A": [1.0, 2.0, 3.0, 4.0], "B": [10.0, 20.0, 30.0, 40.0]}, index=index)

stacked = df2.stack()
print(stacked)
print(stacked.unstack())          # undoes stack (last level by default)
print(stacked.unstack(0))         # unstack another level instead

print(pd.pivot_table(g, values="C", index="A", columns="B", aggfunc="sum"))
first  second
bar    one     A     1.0
               B    10.0
       two     A     2.0
               B    20.0
baz    one     A     3.0
               B    30.0
       two     A     4.0
               B    40.0
dtype: float64
                A     B
first second
bar   one     1.0  10.0
      two     2.0  20.0
baz   one     3.0  30.0
      two     4.0  40.0
first      bar   baz
second
one    A   1.0   3.0
       B  10.0  30.0
two    A   2.0   4.0
       B  20.0  40.0
B    one  three  two
A
bar  2.0    1.0  3.0
foo  2.5    0.5  3.0

Time series

pandas is strong at time-indexed data. resample aggregates by a new frequency, tz_localize attaches a time zone to naive timestamps and tz_convert changes it, and date offsets such as BusinessDay skip weekends:

idx = pd.date_range("2012-01-01", periods=10, freq="min")
ts = pd.Series(np.arange(10), index=idx)
print(ts.resample("5min").sum())
print(ts.head(3).tz_localize("UTC").tz_convert("US/Eastern"))
print(pd.Timestamp("2012-03-09") + pd.offsets.BusinessDay(1))     # a Friday
print(pd.date_range("2024-01-31", periods=3, freq="ME"))
2012-01-01 00:00:00    10
2012-01-01 00:05:00    35
Freq: 5min, dtype: int64
2011-12-31 19:00:00-05:00    0
2011-12-31 19:01:00-05:00    1
2011-12-31 19:02:00-05:00    2
Freq: min, dtype: int64
2012-03-12 00:00:00
DatetimeIndex(['2024-01-31', '2024-02-29', '2024-03-31'],
              dtype='datetime64[us]', freq='ME')

Frequency aliases changed in 2.2 and the old ones were removed in 3.0: month-end is ME (not M), quarter-end QE, year-end YE, hours h (not H), minutes min (not T), milliseconds ms and microseconds us. Period aliases still use M, Q and Y. Time zones use the standard library zoneinfo and pytz is not installed by default.

Categoricals

A categorical column stores a small set of repeated values compactly and can carry an order, which then drives sorting. Renaming categories is cheap; set_categories can add categories that have no rows yet, which groupby then reports only if you ask with observed=False (the default became observed=True in 3.0):

df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]})
df["grade"] = df["raw_grade"].astype("category")
df["grade"] = df["grade"].cat.rename_categories({"a": "very good", "b": "good", "e": "very bad"})
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])

print(df.sort_values(by="grade"))              # by category order, not alphabetically
print(df.groupby("grade", observed=False).size())
print(df.groupby("grade").size())               # observed=True: empty categories omitted
   id raw_grade      grade
5   6         e   very bad
1   2         b       good
2   3         b       good
0   1         a  very good
3   4         a  very good
4   5         a  very good
grade
very bad     1
bad          0
medium       0
good         2
very good    3
dtype: int64
grade
very bad     1
good         2
very good    3
dtype: int64

Plotting

Series.plot and DataFrame.plot draw with Matplotlib (an optional dependency, installed with pandas[plot]) and return the Matplotlib Axes, so you can keep customising with Matplotlib:

import matplotlib.pyplot as plt

ts = pd.Series(np.random.default_rng(1).standard_normal(1000),
               index=pd.date_range("2000-01-01", periods=1000)).cumsum()
ax = ts.plot()
ax.set_title("A random walk")
plt.show()          # in a script; notebooks display the figure automatically

Getting data in and out

Each format has a read_* function and a to_* method. The three most common are CSV (text, universal), Parquet (typed and columnar, the best default for analytical data) and Excel:

d = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("ABC"))

d.to_csv("foo.csv", index=False)
print(pd.read_csv("foo.csv").head(2))

d.to_parquet("foo.parquet")            # needs pyarrow (or fastparquet)
print(pd.read_parquet("foo.parquet").dtypes.to_dict())

d.to_excel("foo.xlsx", sheet_name="Sheet1", index=False)   # needs openpyxl
print(pd.read_excel("foo.xlsx", sheet_name="Sheet1", engine="openpyxl").shape)
   A  B  C
0  0  1  2
1  3  4  5
{'A': dtype('int64'), 'B': dtype('int64'), 'C': dtype('int64')}
(4, 3)

Pass index=False unless the index carries information, otherwise it is written as an extra, unnamed column that you will find again on reading. The Excel and Parquet calls need the optional dependencies described in Installing pandas and Understanding Its Versions; if one is missing pandas raises an ImportError that names the package.

Gotchas

Using a Series in a boolean context, such as if or and, is ambiguous (is a Series "true" when any element is true, or all, or when it is non-empty?) and raises a ValueError that lists the explicit alternatives:

try:
    if pd.Series([False, True, False]):
        pass
except ValueError as exc:
    print(exc)

print(pd.Series([True]).item(), pd.Series([False, True]).any(),
      pd.Series([False, True]).all(), pd.Series([], dtype=float).empty)
The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().
True True False True

For combining masks use the element-wise operators &, | and ~ with parentheses around each comparison, never and, or and not. Adding rows one at a time is slow; build a list of records and construct the frame once:

rows = [{"a": i, "b": i * 2} for i in range(3)]
print(pd.DataFrame(rows))
print(pd.concat([pd.DataFrame({"a": [1]}), pd.DataFrame({"a": [2]})], ignore_index=True))
   a  b
0  0  0
1  1  2
2  2  4
   a
0  1
1  2

What to read next