Bookmarks
ReferenceData & AIVerified

pandas

pandas is a Python library for analysing tabular data. This reference covers DataFrame and dtypes, reading CSV and Parquet, loc and iloc, missing values, groupby, merge and dates.

checked 7 Nov · next check 14 Nov · 67 min read

Sections
13
Reading
67 min
Current version
3.1.1
Written from
pandas.pydata.org/docs

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What pandas is and how it works

pandas is a Python library for analysing tabular data. Its table is a DataFrame: rows and columns carry labels, and each column stores data of its own type.

Typical pandas tasks: read a table from a file or database, remove missing values and duplicates, compute summary figures, join several tables and write out the result. The data must fit in memory; for larger datasets the documentation suggests processing a file in chunks (chunksize) or using a library with distributed computing. A shared table that several programs read and write belongs in a database: pandas keeps its structures in memory and is not designed for concurrent writes.

How a DataFrame is built

A DataFrame is a two-dimensional table, like a SQL table: row labels form the index, and columns have names. Each column is a separate one-dimensional Series with its own data type (dtype): integers, strings and dates are stored differently. You reach a cell by label with loc or by position with iloc.

Each Series has its own dtype: columns of one table store data differently.

Column operations are vectorised: df["amount"] * 1.2 multiplies the whole column at once, with no loop over rows. If two tables have different row labels, pandas aligns them first: values are matched by label, and labels missing on one side produce the missing value NaN. The label-to-value link is preserved in every operation unless you break it manually.

Copy-on-Write: a selection gives a copy

Since pandas 3.0, Copy-on-Write applies: the result of any selection behaves as a copy, and changing it does not affect the original table. There is one rule: you can only modify the object itself. To write a value into the original DataFrame, apply loc to it directly, in a single operation with row labels and a column name.

A typical workflow

pythonanalysis.py
import pandas as pd # read the table into memorydf = pd.read_csv("data.csv")# look at the first rowsprint(df.head())# select rows with large amountsbig = df[df["amount"] > 500]# group and sum the amounts by citysummary = big.groupby("city")["amount"].sum()# write the resultsummary.to_csv("summary.csv")

Each step has its own section: reading and writing files is covered in “Reading and writing data”, selecting rows and columns in “Selection and filtering: loc, iloc, masks”, grouping in “Grouping: groupby”, and joining tables in “Joining tables: merge and concat”.

How pandas differs from NumPy

pandas is built on NumPy and works with its arrays, but for tabular data the differences show immediately.

Featurepandas (DataFrame)NumPy (ndarray)
Labelsrows and columns are labelled: access by label and by positiononly integer positions, no names
Column typeseach column has its own dtypeone dtype for the whole array
Missing valuesa dedicated missing value, NaNno missing value for integers: a column with NaN becomes floating-point
Alignmentoperations match values by labeloperations work by position, element by element
Resizingcolumns and rows can be added and removedsize is fixed at creation
Data shapea table of columns; a Series is one columnan array of any dimensionality

Use a NumPy array for uniform numeric computations without labels; once the data is heterogeneous or you need to select by column name, a DataFrame is more convenient. If you know SQL: pandas operations mirror SELECT, GROUP BY and JOIN — see the correspondence table in the SQL reference, section “SELECT: selecting, filtering and sorting”.

What you need to know first

  • Python basics: variables, lists and dictionaries, functions, loops — see the Python reference, sections “Syntax and control flow” and “Built-in types and data structures”.
  • Project environments and package installation: venv and pip — see the Python reference, section “Modules, packages and dependencies”.
  • The command line: running a script, changing directory — see the Bash reference.

Section sources

the section is written from these pages

Cheat sheet

This cheat sheet collects everyday pandas operations: reading and writing, a first look at a table, selection, cleaning, grouping, joining and dates. Find your task in the left column and take the solution from the right; each operation is explained in its own section of the reference. Replace the names in the examples with your own.

pythonthe examples use this data
import pandas as pd orders = pd.DataFrame({    "order_id": [101, 102, 103, 104],    "customer_id": [1, 2, 1, 3],    "amount": [2500.0, None, 870.5, 1200.0],    "created_at": [        "2026-11-01", "2026-11-02", "2026-11-02", "2026-11-03",    ],})customers = pd.DataFrame({    "customer_id": [1, 2, 3],    "name": ["Aliya", "Timur", "Dilnoza"],})

Reading and writing

TaskHow to write it
Read CSVpd.read_csv("orders.csv")
Read Excelpd.read_excel("orders.xlsx")
Read JSONpd.read_json("orders.json")
Save to CSVorders.to_csv("orders_out.csv", index=False)
Save to Excelorders.to_excel("orders_out.xlsx")
Create a table from a dictionarypd.DataFrame({"amount": [1, 2]})

First look

TaskHow to write it
First rowsorders.head()
Last rowsorders.tail()
Columns and data typesorders.dtypes
Number of rows and columnsorders.shape
Summary: columns, types, missing valuesorders.info()
Statistics for numeric columnsorders.describe()

Selection

TaskHow to write it
One columnorders["amount"]
Rows and columns by labelorders.loc[0, "amount"]
Rows by positionorders.iloc[0]
A range of rows by positionorders.iloc[:10]
Rows by maskorders[orders["amount"] > 1000]
Rows by expressionorders.query("amount > 1000")
Several conditionsorders[(orders["amount"] > 1000) & (orders["customer_id"] == 1)]
Filter by a list of valuesorders[orders["customer_id"].isin([1, 2])]
Select columns by typeorders.select_dtypes("number")

Cleaning

TaskHow to write it
Find missing valuesorders.isna()
Count missing values per columnorders.isna().sum()
Fill missing valuesorders["amount"].fillna(0)
Drop rows with missing valuesorders.dropna()
Remove duplicatesorders.drop_duplicates()
Rename columnsorders.rename(columns={"amount": "total"})
Change a column’s typeorders["order_id"].astype("str")
New value by conditionorders["big"] = orders["amount"] > 1000

Grouping

TaskHow to write it
Sum by grouporders.groupby("customer_id")["amount"].sum()
Several aggregationsorders.groupby("customer_id").agg(total=("amount", "sum"), n=("order_id", "count"))
Number of rows per grouporders.groupby("customer_id").size()
Value frequenciesorders["customer_id"].value_counts()
Mean of a columnorders.groupby("customer_id")[["amount"]].mean()

Joining

TaskHow to write it
Join on a columnorders.merge(customers, on="customer_id")
Keep all rows of the left tableorders.merge(customers, on="customer_id", how="left")
Stack tables verticallypd.concat([orders, orders2])
Continue the row numberingpd.concat([orders, orders2], ignore_index=True)

Dates

TaskHow to write it
Convert strings to datesorders["created_at"] = pd.to_datetime(orders["created_at"])
Year and monthorders["created_at"].dt.to_period("M")
Sum by dayorders.resample("1D", on="created_at")["amount"].sum()
Mean by monthorders.resample("1ME", on="created_at")["amount"].mean()
Sort by timeorders.sort_values("created_at")

Watch out

TaskHow to write it
Mean of a column with missing valuesorders["amount"].mean() — skips NaN by default
Comparing with a missing valueorders["amount"] == None gives False everywhere — use isna() only
Adding rows in a loopAfter the loop, pass a list of dictionaries to pd.DataFrame — adding rows one by one with concat is slow
  • Selection and filtering: loc, iloc, masks — covers .loc, .iloc, masks and query.
  • “Missing values” — covers isna, fillna, dropna.
  • “Grouping: groupby” — covers groupby and aggregations.
  • “Joining tables: merge and concat” — covers merge and concat.
  • “Dates and time series” — covers to_datetime and resample.

Section sources

the section is written from these pages

Installation and first run

Install pandas into a virtual environment with pip install pandas, or through conda from the conda-forge channel. Check the installation with python -c "import pandas; print(pandas.__version__)".

Requirements

pandas 3.1 needs Python 3.11 or newer and NumPy 2.0.2 or newer: support for NumPy 1.x has ended. pandas takes its supported Python versions from the SPEC 0 recommendation: a version is dropped three years after its release. The minimum version of a required dependency is the one released about two years before the pandas release, and of an optional dependency about one year before.

Linux

Create a virtual environment and install pandas into it; the commands are the same for all Linux distributions, because PyPI packages do not depend on the system package manager. For how venv works, see the Python reference, section “Installation and first run”.

bashon the host
python3 -m venv .venvsource .venv/bin/activatepip install pandas

macOS and Windows

The commands are the same as on Linux; on Windows the environment is activated with .venv\Scripts\activate. The alternative to pip is conda, a package manager for the scientific Python stack that installs Python itself along with pandas and its dependencies. The recommended way to install conda is the Miniforge distribution; pandas is officially distributed for conda through the conda-forge channel:

bashin a terminal
conda create -c conda-forge -n pandas-env python pandasconda activate pandas-env

Optional dependencies

Optional dependencies enable individual methods: read_hdf requires tables, and to_markdown requires tabulate. If a package is not installed, the method fails with ImportError when called. With pip, such packages are installed in groups called extras:

ExtraWhat it provides
pandas[performance]speed-ups: numexpr, bottleneck, numba
pandas[excel]reading and writing Excel, including openpyxl, xlsxwriter, python-calamine
pandas[postgresql, mysql, sql-other]SQL drivers: SQLAlchemy, psycopg2, pymysql
pandas[parquet]the Parquet and feather formats through pyarrow
pandas[fss, aws, gcp]reading files from the cloud: fsspec, s3fs, gcsfs
pandas[all]all optional dependencies
bashin the environment
pip install "pandas[excel]"# combine extras with commaspip install "pandas[performance, aws]"

For Parquet, a columnar format for large datasets, the pandas[parquet] extra from the table installs the pyarrow library: with it, pandas reads and writes Parquet by default (the fastparquet engine is installed separately).

The documentation calls the pandas[performance] extra recommended: numexpr and bottleneck speed up numeric operations on large datasets. The minimum dependency versions in the tables on the installation page apply to pandas 3.1; other releases differ.

Checking the installation

If pandas is not installed, import pandas fails with an error, so the command also checks the installation. The pandas version is printed by the __version__ attribute.

bashin the environment
python -c "import pandas; print(pandas.__version__)"

The pd.show_versions() function prints the full list of versions for a bug report: the operating system, the pandas version and the versions of all installed dependencies. The as_json=True parameter switches the output to JSON.

bashin the environment
python -c "import pandas as pd; pd.show_versions()"
textexample output
INSTALLED VERSIONS------------------commit           : ...python           : 3.13.7.final.0OS               : Linuxpandas           : ...numpy            : ......

Your first project

A pandas project directory usually looks like this:

textdirectory layout
pandas-demo/├── .venv/           # virtual environment├── requirements.txt # list of dependencies├── data/            # data files└── analyze.py       # script

List project dependencies in requirements.txt, one per line. You can leave a package without a version if the latest version from PyPI is enough for the project. Install them with pip install -r requirements.txt.

textrequirements.txt
pandaspandas[performance]

To run for the first time: create the environment, install the dependencies, put the data in data/ and run the script from the activated environment. Instead of a script you can use a Jupyter notebook; see the Python reference for details.

bashin the project directory
# once: environment and dependenciespython3 -m venv .venvsource .venv/bin/activatepip install -r requirements.txt # every working sessionpython analyze.py

Section sources

the section is written from these pages

Series, DataFrame, Index and dtypes

A Series is a column of values with labels, and a DataFrame is a set of such columns sharing row labels. A column’s data type (dtype) determines what it holds, and Copy-on-Write makes every selection a copy: modify data only through loc.

Series: values, index, name

A Series is a one-dimensional array of values with labels. The labels together are called the index. From a list, pandas builds an index of consecutive integers; from a dictionary, an index of its keys; and if you pass an index as a list, any values without a match become missing.

python
import pandas as pd s = pd.Series([1200, 850, 430], index=["tea", "coffee", "water"])d = pd.Series({"b": 1, "a": 0})  # labels from the dictionary keyss.name = "amount"                # column name if the Series leaves its table

In operations, two Series are aligned by label, not by order: each label is looked up in both. If a label exists in only one, the result contains NaN, so pandas never silently loses data; remove the empty labels with dropna (see the section “Missing values”).

python
a = pd.Series([1, 2], index=["x", "y"])b = pd.Series([10, 20], index=["y", "z"])a + b          # x and z give NaN: the label exists on one side only

DataFrame: rows and columns

A DataFrame is a two-dimensional table whose columns can have different types. It is most often built from a dictionary of lists: the keys become column names and the lists become values. A column is retrieved like a dictionary item and is itself a Series.

python
df = pd.DataFrame({    "city": ["Tashkent", "Samarkand", "Bukhara"],    "pop": [2900, 560, 250],})df["pop"]        # the pop column, a Series named popdf["area"] = [256, 92, 39]   # a new column at the enddel df["area"]               # deletion, as with a dictionary

A list of dictionaries works when records differ in length: a missing key becomes NaN. This suits data collected row by row, for example from JSON.

python
rows = [{"a": 1, "b": 2}, {"a": 5, "c": 20}]pd.DataFrame(rows)#    a    b     c# 0  1  2.0   NaN# 1  5  NaN  20.0

Rows and columns are compared in operations between two tables: alignment happens on both row labels and column names.

Index: row labels

The index is not a row number but a persistent label. By default it is a RangeIndex of consecutive integers, but you can make meaningful values the labels: the set_index method turns a column into the index, and reset_index moves the labels back into a column.

python
df = pd.DataFrame({    "city": ["Tashkent", "Samarkand", "Bukhara"],    "pop": [2900, 560, 250],})df = df.set_index("city")    # select by city: df.loc["Bukhara"]df = df.reset_index()        # the labels go back into the city column

Labels may repeat: the index does not have to be unique. Select data by label with loc and by position with iloc (see the section “Selection and filtering”).

Column types

pandas picks a column’s data type (dtype) on creation: whole numbers become int64, numbers with a fractional part float64, logical values bool, and dates datetime64. Check the types of all columns with df.dtypes, and of a single column with df["pop"].dtype.

Since pandas 3.0, strings are stored in a dedicated str type rather than object: the str type accepts only strings, and a missing value is shown as NaN, as in the numeric types. The old object remains for mixed values, and such a value cannot be written into the new type.

TypeWhen it appears
int64integers: counters, identifiers
float64numbers with a fractional part; appears when a column contains NaN
booltrue and false with no missing values
datetime64dates and times (see the section “Dates and time series”)
strtext by default since pandas 3.0
Int64, booleanlike int64 and bool, but accept missing values
categoryrepeated strings: statuses, cities, categories
int64[pyarrow]PyArrow-backed types: they save memory and are read from Parquet

Types with a capital letter, such as Int64, boolean and Float64, allow missing values inside integer and logical data, where an ordinary int64 has to become float64. Types marked [pyarrow] store data in the Apache Arrow format; you can enable them for all columns when reading with the dtype_backend="pyarrow" parameter of read_csv and read_parquet, and with the dtype_backend parameter of convert_dtypes.

Type conversion and memory

Change a type with the astype method: pass it a type name or a dictionary of column-to-type pairs. An impossible conversion, such as "x" to a number, raises an error. The convert_dtypes method picks types itself: numbers with missing values become Int64, strings become string, and logical values become boolean.

python
df["pop"] = df["pop"].astype("int32")df = df.astype({"pop": "int32", "city": "category"})df = df.convert_dtypes()   # pick types, allowing for missing values

df.info(memory_usage="deep") shows how much memory a table takes: it counts the actual strings rather than estimating from the type. Convert a column with repeated strings to category: pandas stores the list of unique values once, and the cells hold only category numbers.

python
s = pd.Series(["foo", "bar"] * 500)print(s.memory_usage(deep=True))               # 60132 bytesprint(s.astype("category").memory_usage(deep=True))  # 1252 bytes

Copy-on-Write: a selection is a copy

Since pandas 3.0, Copy-on-Write applies: any selection returns an object that does not share data with the original table. Changing a selection never changes the original table any more. The behaviour is now predictable, but code that relied on the old behaviour breaks.

python
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})subset = df["foo"]subset.iloc[0] = 100df            # foo is still 1: a copy was modified, not the table

A conditional replacement is also done in one step with loc: a row mask on the left and a column name on the right. The chain df["a"][df["b"] > 5] = 1, by contrast, does not change the table and raises the warning.

python
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})df.loc[df["bar"] > 4, "foo"] = 100# rows where bar is greater than 4 now have foo = 100

For a table whose columns all have the same type, the array from to_numpy() shares memory with the table and is therefore read-only: writing to it raises ValueError. Copy the array with .copy() if you need to modify it independently of the table.

Section sources

the section is written from these pages

Reading and writing data

pandas reads and writes CSV, Excel, JSON, Parquet and database tables in pairs: pd.read_csv returns a DataFrame, and DataFrame.to_csv saves it to a file. Use CSV to exchange data with people, Parquet for large datasets and backups, and Excel for reports.

Some formats need optional dependencies: openpyxl for Excel, pyarrow for Parquet, and SQLAlchemy with a driver for your DBMS for databases. SQLite needs only the Python standard library.

python
import pandas as pd df = pd.read_csv("orders.csv")
FormatReadsWritesDependency
CSVread_csvDataFrame.to_csvnone
Excelread_excelDataFrame.to_excelopenpyxl
JSONread_jsonDataFrame.to_jsonnone
Parquetread_parquetDataFrame.to_parquetpyarrow
SQLread_sqlDataFrame.to_sqlSQLAlchemy or sqlite3

CSV: reading and writing

Three engines can parse CSV, selected with the engine parameter: c (the default), pyarrow (requires the pyarrow package) and python. The c and pyarrow engines are faster; python is slower but supports regular expressions in sep and the skipfooter parameter. The usecols parameter speeds up reading because unwanted columns are not parsed. pandas decompresses .gz, .bz2, .zip and .xz files on the fly, detecting the compression from the file extension.

pythona file in a Windows encoding
df = pd.read_csv(    "orders.csv",    sep=";",    encoding="cp1251",    usecols=["date", "amount"],    dtype={"amount": "float64"},    parse_dates=["date"],    nrows=1000,)
ParameterDefaultWhat it does
sep","delimiter; sep=None detects it from the first line, but only with the python engine
dtypenot setpandas infers the types; a dictionary sets column types, for example to keep codes as strings
usecolsnot setkeep only the named columns, which makes reading faster
parse_datesnot setparse the listed columns as dates; date_format sets the format
encoding"utf-8"file encoding, for example cp1251 for exports from Windows programs
nrowsnot setread this many rows of data, to get a feel for a large file
chunksizenot setreturn an iterator over chunks of this many rows
engine"c"parsing engine: c, python or pyarrow

To write a table back, use to_csv. By default it also writes the index as a separate column, which is usually unwanted, so turn it off with index=False. The encoding parameter sets the encoding and sep the delimiter; for both read_csv and to_csv the defaults are UTF-8 and a comma.

python
df.to_csv("orders_out.csv", index=False, sep=";", encoding="utf-8")

Large files and chunks

Since 3.1, large local CSV files are read with several threads: the c engine splits the file into parts and parses them in parallel. This happens automatically for an uncompressed local file of 5 MB or more when no parameter that needs the whole file is set, such as iterator, chunksize, nrows, usecols, index_col or parse_dates. The result is identical to sequential reading. The mode.max_threads option limits the number of threads: by default it is the number of cores available to the process, up to 6, and 1 restores sequential reading.

python
# inside an application that already parallelises its workwith pd.option_context("mode.max_threads", 1):    df = pd.read_csv("large.csv")

If a table does not fit in memory, or processing is easier in steps, read it in chunks: the chunksize parameter returns an iterator of DataFrames. nrows reads only the first rows, so you can explore a file without opening all of it.

python
# the first 100 rowsdf = pd.read_csv("large.csv", nrows=100) # process in chunks of 50,000 rowswith pd.read_csv("large.csv", chunksize=50_000) as reader:    total = sum(len(chunk) for chunk in reader)

Excel: reading and writing

Excel is read sheet by sheet. The sheet_name parameter accepts a sheet name, a number or a list; by default the first sheet is read, and sheet_name=None returns a dictionary of all sheets. to_excel writes a file, and pd.ExcelWriter puts several tables in one file.

python
df = pd.read_excel("report.xlsx", sheet_name="Sales") with pd.ExcelWriter("result.xlsx") as writer:    df.to_excel(writer, sheet_name="Summary", index=False)    # the second table is another DataFrame    totals.to_excel(writer, sheet_name="Details", index=False)

Parquet

Parquet is a binary columnar format. Files are more compact than CSV, and column types survive a write and read, including time-zone-aware dates and nullable types. It needs the pyarrow package. As with CSV, index=False skips the index, and columns= in read_parquet reads only the named columns.

python
df.to_parquet("orders.parquet", index=False)df = pd.read_parquet("orders.parquet", columns=["date", "amount"])

JSON and JSON Lines

How JSON becomes a table depends on the shape of the records. The orient parameter sets that shape and is the same for writing and reading. For logs and streams, JSON Lines (JSONL) is convenient: each line of the file is one object, enabled with lines=True. With chunksize, reading proceeds in chunks of that many lines.

python
df.to_json("orders.jsonl", orient="records", lines=True)df = pd.read_json("orders.jsonl", lines=True)

SQL: reading and writing

Databases need SQLAlchemy and a driver for your DBMS (psycopg2 for PostgreSQL, pymysql for MySQL). Create an engine with create_engine from a connection URI, one object per database. read_sql accepts both a table name and a query. to_sql creates a table or appends to an existing one, as set by if_exists: fail by default, replace recreates the table, and append adds rows to it. pandas picks column types itself; override them with the dtype parameter, whose values are SQLAlchemy types.

python
from sqlalchemy import create_engine engine = create_engine("postgresql://app:change-me@localhost/shop") df = pd.read_sql_table("orders", engine)df.to_sql("orders_2026", engine, if_exists="replace", index=False)
pythona query with a parameter
import sqlalchemy as sa query = sa.text("SELECT * FROM orders WHERE amount > :min")df = pd.read_sql(query, engine, params={"min": 1000})

Use a database when several applications read the same tables. Once loaded, the data is filtered like any other pandas table; see the “Selection and filtering” section, and the “Missing data” section for handling absent values.

Section sources

the section is written from these pages

Selection and filtering: loc, iloc, boolean masks

Selection reads part of a table: individual columns, rows, or their intersection. Columns are taken by name (df[["a", "b"]], loc) or by position (iloc); rows are chosen with a boolean mask or with query().

The examples below use this table:

pythonthe table used in all code blocks
import pandas as pd df = pd.DataFrame(    {        "city": ["Tashkent", "Samarkand", "Bukhara", "Khiva", "Nukus"],        "population": [3016000, 565000, 250000, 93000, 312000],        "founded": ["2019-01-01", "2020-06-01", "2021-09-01",                    "2022-05-01", "2023-03-01"],    })df["founded"] = pd.to_datetime(df["founded"])

Columns: Series or DataFrame

A single column in square brackets is a Series; a list of columns gives a new table. The list always needs double brackets: df[["city"]].

python
# one column: a Seriesdf["population"]# a list in double brackets: a new tabledf[["city", "population"]]

loc and iloc: labels or positions

loc selects rows and columns by label (index), iloc by integer position, counting from zero. A label and a position coincide only while the index is unchanged: in the example table the row labelled 2 is at position 2, but after sort_values they are different things.

Featurelociloc
Keylabelzero-based position
ErrorsKeyError if the label is missingIndexError if the position is out of range
Sliceincludes the right boundexcludes the right bound
Exampledf.loc["b", "population"]df.iloc[1, 1]
python
# labels: rows 1–3 and columns from city to populationdf.loc[1:3, "city":"population"]# positions: rows 1 and 2, columns 0 and 1df.iloc[1:3, 0:2]

A slice by label includes the right bound: df.loc[1:3, "city":"population"] returns rows 1, 2 and 3, while the same slice by position in iloc would return only rows 1 and 2.

Masks: and, or, not

Comparing a column produces a boolean mask: a column of True and False values as long as the table. Putting a mask in [] or loc keeps the rows where it is True.

pythonmasks from comparisons and checks
df.loc[df["population"] > 500000, "city"]df[df["population"].between(100000, 600000)]df[df["city"].isin(["Samarkand", "Nukus"])]df[df["city"].str.contains("and", regex=False)]

Combine conditions with the operators & (and), | (or) and ~ (not); the keywords and, or and not do not work. Wrap each condition in parentheses: & binds more tightly than >, so without them a > 1 & b < 2 compares 1 & b.

pythonparentheses around each condition are required
df[(df["population"] > 300000) & (df["founded"].dt.year > 2020)]df[(df["city"] == "Khiva") | (df["city"] == "Nukus")]df[~df["city"].str.startswith("S")]

query(): conditions as a string

query() takes an expression as a string. No parentheses are needed, and, or, not and in work as in Python, and the row label is available as index.

pythonuse single quotes inside
df.query("population > 200000 and city != 'Tashkent'")df.query("city in ['Samarkand', 'Nukus']")

select and filter in a method chain

pandas 3.1 adds select() and a cond parameter on filter() for method chains. df.select() returns a table of the listed columns and of columns computed with pd.col():

python
df.select("city", pd.col("population"),          mln=pd.col("population") / 1_000_000)

df.filter(cond=…) keeps the rows where the mask is true, an alternative to df[mask] inside a chain. cond can be a mask, a pd.col() expression or a function. In select, a function can only be passed as a keyword argument (name=function).

pythoncond= is named explicitly; it can also be passed positionally
df.filter(cond=pd.col("population") > 300000)df.filter(lambda df: df["city"] != "Khiva")

Sorting and top values

sort_values() sorts by a column or a list of columns. nlargest(n, …) and nsmallest(n, …) return the n rows with the largest or smallest values, which is faster than sorting and calling head(n).

python
df.sort_values("population", ascending=False).head(2)df.nlargest(2, "population")df.nsmallest(2, "population")

Changing values and Copy-on-Write

To assign a value to part of a table, do it in one step with loc: a mask and a column to the left of =, the value to the right.

pythonone assignment, one loc call
df.loc[df["population"] > 500000, "population"] = Nonedf.loc[0, "city"] = "Toshkent"

Learn more

Values that do not exist become missing values in a selection; see the “Missing data” section for what to do with them. To expand a mask back into a table of the same shape, use where(). Ready-made recipes for these and related operations are in the cheat sheet. Joining tables on keys is not selection; see the “Merging tables: merge and concat” section. If you know SQL, a mask works like WHERE.

Section sources

the section is written from these pages

Missing data

A missing value is an absent value in a table. pandas marks it with a sentinel: NaN, pd.NA, NaT or None, depending on the column type. Find missing values with isna(), remove them with dropna(), and fill them with fillna(), ffill() and interpolate().

The examples use this table of city visits:

pythonthe table used in all code blocks
import pandas as pd df = pd.DataFrame(    {        "city": ["Tashkent", "Samarkand", "Bukhara", None],        "visitors": [3016, 565, None, 93],        "rating": [4.5, None, 4.1, 3.9],    })

How pandas marks a missing value

The sentinel depends on the column’s data type (dtype). For NumPy numbers it is np.nan, and the column is converted to float64. A boolean column becomes object, and the missing value stays as it arrived: None or NaN. In dates it is pd.NaT. In nullable types (Int64, boolean, Float64) and ArrowDtype it is pd.NA, and the column keeps its original type.

Column typeSentinelEffect on the type
int64np.nanthe column is converted to float64
boolNone or NaNthe column becomes object
datetime64, timedelta64, periodpd.NaTthe type is kept
nullable: Int64, Float64, booleanpd.NAthe type is kept
strings: str (the default since pandas 3.0)np.nanthe type is kept

None in data is also a missing value: isna() treats it as missing. But it is stored differently: in ordinary numeric columns, None becomes NaN. In the str string type, the default since pandas 3.0, any missing value, None or NaN, is stored as NaN.

pythonPython, interactive
# None in a numeric column becomes NaN,# and the column changes from int64 to float64df["visitors"].dtype # string dtype: None is stored as NaN, not as pd.NAs = pd.Series(["a", None])repr(s[1])     # 'nan's[1] is pd.NA  # Falsepd.isna(s[1])  # True

Finding missing values: isna

isna() returns a boolean mask that is true where a value is missing; notna() does the opposite. The comparison df == np.nan does not work because NaN is not equal even to itself. Always test for missing values with isna().

pythonexample output
df.isna().sum()# city        1# visitors    1# rating      1 df.dropna()# only rows without any missing value remain

By default dropna() removes rows that have a missing value in at least one column (how="any"). Parameters narrow the condition:

ParameterWhat it doesDefault
axis0 for rows, 1 for columns0
how"any" if at least one value is missing, "all" if all are"any"
subsetthe columns to checkall columns
threshkeep rows with at least N non-missing valuesnone
python
# rows with at least 2 non-missing valuesdf.dropna(thresh=2) # rows where city is filled indf.dropna(subset=["city"]) # columns without missing valuesdf.dropna(axis=1)

Filling: fillna, ffill, interpolate

fillna(value) replaces missing values with a number, a string, or a dictionary of column-to-value pairs for different columns. Use zero only when it makes sense for the column: zero visitors is a measured fact (“nobody came”), not a missing measurement. For a rating, the column mean is more honest.

python
# zero where it fits the column, the mean for the ratingdf.fillna({"visitors": 0, "rating": df["rating"].mean()}) # with the column meandf["rating"].fillna(df["rating"].mean())

ffill() carries the last known value forward, and bfill() carries the next known value backward. This makes sense for time-ordered data where the value rarely changes, such as an exchange rate or a tariff. interpolate() computes intermediate values from neighbouring points, linearly by default; for data with dates in the index there is method="time".

MethodWhat it doesWhen to use it
fillna(x)replaces a missing value with xa constant that makes sense: 0, “unknown”
ffill()takes the last known valuethe value rarely changes
bfill()takes the next known valuethe same, when backward is more correct
interpolate()computes an intermediate valuea numeric series with equal steps
dropna()removes rows or columns with missing valuesthere are few missing values and they do not matter
python
# a dataset with gaps in a series indexed by datets = pd.Series(    [1.0, None, None, 7.0],    index=pd.to_datetime(        ["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04"]    ),)ts.ffill()# 2026-01-01    1.0# 2026-01-02    1.0# 2026-01-03    1.0# 2026-01-04    7.0 ts.interpolate()# 2026-01-01    1.0# 2026-01-02    3.0# 2026-01-03    5.0# 2026-01-04    7.0

pd.NA and nullable types

In nullable types a missing value is a separate object, pd.NA. It propagates through arithmetic (pd.NA + 1 is pd.NA) and comparisons: pd.NA == 1 gives <NA>, not False. Keep a number with missing values in Int64 rather than float64: the sum stays an integer (3581, not 3581.0) and the column stays integer.

python
visitors = pd.Series([3016, 565, None], dtype="Int64")visitors# 0    3016# 1     565# 2    <NA># dtype: Int64 visitors.sum()  # 3581

Comparing with pd.NA returns <NA>, not False. So wherever Python needs a definite answer, such as if, and or all(), an error is raised:

pythonraises the error described in the note below
if pd.NA:    ...

The logic is three-valued: True & NA is <NA>, False & NA is False, True | NA is True. When selecting with a boolean mask, <NA> counts as False; if that is not what you want, fill the mask first: mask.fillna(False).

Missing values in grouping

By default groupby() does not create a group for a missing key: rows with a missing value in the grouping column disappear from the result. To see them as a separate group, pass dropna=False.

pythonexample output
df.groupby("city", dropna=True)["visitors"].sum()# Bukhara       0.0# Samarkand   565.0# Tashkent   3016.0 df.groupby("city", dropna=False)["visitors"].sum()# NaN          93.0

Sums and means skip missing values by default: df.sum() adds up the non-missing values, and skipna=False includes missing values in the calculation, which makes the total NaN. Aggregation is covered in detail in the “Grouping: groupby” section.

Section sources

the section is written from these pages

Grouping: groupby

Grouping splits a table into groups by the values of key columns, computes a result for each group and assembles the results into a new table. In pandas it starts with df.groupby(...); agg computes the results, transform puts each group’s value next to every row, and filter selects whole groups.

The examples use a table of orders: the columns are city, amount and qty, and the rows are orders from Tashkent, Samarkand and Nukus.

pythonthe table used in all code blocks
import pandas as pd orders = pd.DataFrame(    {        "city": ["Tashkent", "Samarkand", "Tashkent",                 "Nukus", "Samarkand", "Tashkent"],        "amount": [1200, 340, 450, 90, 510, 300],        "qty": [2, 1, 3, 1, 2, 1],    })
split-apply-combine: the sum of amount by city.

Group results: agg

The groupby call itself computes nothing: it returns a GroupBy object that knows how to divide the rows and waits for an operation. The main operation is aggregation: a function receives all the rows of a group and returns a single value. The built-in aggregations are the methods sum(), mean(), count(), min(), max(), median(), std() and nunique().

pythonthe sum of one column
(orders.groupby("city")["amount"]   .sum())# city        amount# Nukus       90# Samarkand   850# Tashkent    1950

The built-in methods have their own efficient implementation inside pandas. To compute over several columns or with several functions, use agg: a list of names gives several result columns for each column, and a dictionary assigns each column its own function.

pythonseveral functions at once
orders.groupby("city")[["amount", "qty"]].agg(["sum", "mean"])# sum and mean for each column orders.groupby("city").agg({"amount": "sum", "qty": "max"})

Named aggregation sets the names of the result columns with arguments of the form name=(column, function). Clear names are easier to read and to select later.

pythonnamed aggregation
out = orders.groupby("city").agg(    total=("amount", "sum"),    orders=("amount", "count"),    avg=("amount", "mean"),)# result columns: total, orders, avg; the city key is in the index

By default the group keys become the index of the result. The as_index=False parameter returns them as ordinary columns, which is what an SQL query with GROUP BY gives you. The other way is to keep the index and call reset_index(), which is convenient with a MultiIndex from several keys.

pythonkeys as ordinary columns
orders.groupby("city", as_index=False).agg(    total=("amount", "sum"))

Several keys and their parameters

You can group by a list of columns, for example city and qty; by default the result gets a MultiIndex of the keys. Three groupby parameters control the result: sort=True sorts groups by key (turn it off for speed and to keep the order of the data), observed applies to grouping by a category column, and dropna=True drops rows with NaN in the key.

pythontwo keys, in the order of the data
orders.groupby(["city", "qty"], as_index=False,              sort=False).agg(total=("amount", "sum"))

By default (dropna=True), rows with NaN in the key column fall out of every group, so totals may not add up to the number of rows. To keep groups with an empty key, pass dropna=False (see the “Missing data” section).

transform: the group result next to every row

Aggregation shrinks the table to the number of groups, while transform returns a column as long as the original table: each row gets the result for its group. Use it for new columns such as a row’s share of its group, its deviation from the mean, or its number within the group (cumcount).

pythonshare and deviation within a group
orders["share"] = (orders["amount"]    / orders.groupby("city")["amount"].transform("sum"))orders["dev"] = (orders["amount"]    - orders.groupby("city")["amount"].transform("mean"))

transform accepts both the name of a built-in aggregation ("sum", "mean", whose result is broadcast across the group) and your own functions. A custom function returns either as many values as the group has rows, or a single value for the whole group.

filter: keep groups by a condition

filter receives each group whole: if the function returns True, the group’s rows stay in the table, and if False, they are dropped. The output has the same columns, without the rows of the discarded groups.

pythonsingle-row groups are dropped entirely
big = orders.groupby("city").filter(    lambda g: g["amount"].sum() >= 500)# Tashkent and Samarkand remain orders.groupby("city").filter(lambda g: len(g) > 1)

apply: when no built-in method fits

apply passes each group to your function and infers from its result what to do next: combine, broadcast or filter. The result can change shape and index, and apply is slow because the function is called in Python for every group. Look first for a solution with agg, transform or filter, which are faster and more predictable in shape.

pythonsome tasks that look like apply do not need it
# the top 2 orders of each citytop = (orders    .sort_values("amount", ascending=False)    .groupby("city")    .head(2))

You cannot do without apply when the result is not a single function over columns: the function sees the whole group and returns a table or a value of any shape. apply infers from the result whether the group keys go into the index, and it can get this wrong; set group_keys=False if you do not want the keys in the index.

Counting rows in a group, and what counts where

size() gives the number of rows in each group. value_counts() counts the occurrences of each value, and count() counts the non-missing values of the selected column.

pythongroup sizes
orders.groupby("city").size()# Nukus        1# Samarkand    2# Tashkent     3 orders["city"].value_counts()
TaskMethodReturns
one number per groupagga table with one row per group
each group’s result for every rowtransforma column as long as the original table
keep or drop groupsfilterthe rows of the surviving groups
an arbitrary function over a groupapplya shape that depends on the function
group sizesize, value_countsa Series with one row per group

A pivot table is the same grouping with keys along both rows and columns: pivot_table computes an aggregate at the intersection of the values of two columns. For details, see the pandas reference, section “Reshaping: pivot, melt, stack”.

If you know SQL: groupby mirrors GROUP BY. The keys become the rows of the result, and agg plays the role of the aggregate functions. For details, see the SQL reference, section “Aggregate functions and GROUP BY”.

  • groupby only divides the rows; the next call computes the results: agg, transform, filter or apply.
  • Named aggregation agg(total=("amount", "sum")) gives the result clear column names.
  • as_index=False keeps the keys as ordinary columns; sort=False preserves the order of the data and speeds up the call.
  • transform returns a column as long as the original table, which is how you add a group’s share or deviation to every row.
  • Rows with NaN in the key are dropped (dropna=True); empty category categories are not shown (observed=True).

Section sources

the section is written from these pages

Joining tables: merge and concat

Join two tables on a key with merge(), the same way VLOOKUP and SQL joins work. To stack tables or place them side by side without a key, use concat().

The examples below use orders and a customer lookup table. Order 104 has no customer in the lookup table, which shows how the join types differ.

pythonexample used by all the code blocks below
import pandas as pd orders = pd.DataFrame({    "order_id": [101, 102, 103, 104],    "customer_id": [1, 2, 2, 3],    "total": [1500, 2400, 320, 890],})customers = pd.DataFrame({    "customer_id": [1, 2],    "name": ["Anvar", "Dilnoza"],})
how="left": every row of orders is kept, and 104 gets NaN instead of a name.

merge: join types

merge() looks for matching key values and builds each row from the columns of both tables. The key is a column shared by both tables, passed as on; if the names differ, use left_on and right_on. Without them, the join uses all shared columns. The how parameter decides whose keys end up in the result. The names follow SQL, and the default is inner. For the SQL equivalents, see the sql reference.

howResult
"inner"only keys present in both tables
"left"all rows of the left table; unmatched rows get NaN on the right
"right"all rows of the right table; unmatched rows get NaN on the left
"outer"all keys from both tables, with matches combined
"cross"every pair: each row with each row
"left_anti"rows of the left table with no match in the right
"right_anti"rows of the right table with no match in the left
pythoninner drops rows, left keeps everything on the left
orders.merge(customers, on="customer_id", how="inner")# 3 rows: orders 101–103; order 104 is droppedorders.merge(customers, on="customer_id", how="left")# 4 rows: order 104 has name = NaN

If the key names differ, use the left_on and right_on pair:

python
right = pd.DataFrame({"ref": [1, 2], "name": ["Anvar", "Dilnoza"]})orders.merge(right, left_on="customer_id", right_on="ref")

List the columns for a composite key: on=["city", "street"]. With inner and left, rows follow the order of the left table; with outer, the keys are sorted.

Duplicate columns and suffixes

When non-key columns share a name, pandas tells them apart with suffixes: by default, the left table gets _x and the right gets _y. Set your own with suffixes.

python
q1 = pd.DataFrame({"city": ["Tashkent"], "temp": [9]})q2 = pd.DataFrame({"city": ["Tashkent"], "temp": [12]})q1.merge(q2, on="city")            # temp_x, temp_yq1.merge(q2, on="city", suffixes=("_jan", "_feb"))

The validate and indicator checks

If a key repeats in the lookup table, each row of the left table is multiplied by every match: two orders and two rows for the same customer give four rows, and the totals per customer double. validate records your assumption about the keys: if a side breaks it, the join fails with MergeError before doing any work.

validateWhat you promiseChecked on
"one_to_one"the key is unique in both tablesboth
"one_to_many"unique on the leftleft
"many_to_one"unique on the rightright
"many_to_many"nothing—
pythonthe lookup table is unique, so this is a many-to-one join
orders.merge(customers, on="customer_id",             how="left", validate="many_to_one")

To see where each row came from, use indicator=True: it adds a _merge column with the values both, left_only or right_only. With how="outer", this shows the unmatched keys of both tables.

pythonunmatched rows by _merge
result = orders.merge(    customers, on="customer_id", how="outer", indicator=True)result[result["_merge"] != "both"]# only order 104 is left: left_only

join: joining on the index

df.join(other) joins on the index and works as how="left" by default. It is convenient when the row labels are the keys: article numbers, dates, tickers.

pythonthe index as the key
prices = pd.DataFrame({"price": [99, 149]}, index=["A", "B"])stock = pd.DataFrame({"stock": [5, 0]}, index=["A", "C"])prices.join(stock)# B gets stock = NaN; row C = 0 does not appear

To join on a column with join, pass it as on; the key of the second table is still its index.

concat: stacking by rows and columns

pd.concat() takes a list of tables and attaches them one under another (axis=0, the default) or side by side (axis=1). Columns are matched by name; where a column is missing, you get NaN.

pythonone column for the month
jan = pd.DataFrame({"city": ["Tashkent", "Samarkand"],                    "temp": [9, 12]})feb = pd.DataFrame({"city": ["Tashkent", "Bukhara"],                    "temp": [12, 15]})pd.concat([jan, feb], ignore_index=True)

Without ignore_index=True, the row labels of the pieces repeat: both jan and feb have a row 0, so looking up label 0 later returns two rows. For tables without a meaningful index, always reset it.

With keys=["jan", "feb"], each piece gets its own label in an outer index level, so the source of each piece stays visible. Name that level with names=["month"]:

pythonby month index
mar = pd.DataFrame({"city": ["Tashkent"], "temp": [17]})by_month = pd.concat([jan, feb, mar],                     keys=["jan", "feb", "mar"],                     names=["month"])by_month.loc["feb"]

With axis=1, tables are placed side by side and aligned on the index: rows with the same label line up, and missing ones get NaN. join="inner" keeps only the labels present in all tables.

pythonside by side with alignment
q1 = pd.DataFrame({"q1": [10, 20]}, index=["x", "y"])q2 = pd.DataFrame({"q2": [1, 2]}, index=["y", "z"])pd.concat([q1, q2], axis=1)        # NaN in the cornerspd.concat([q1, q2], axis=1, join="inner")

merge_asof: nearest time instead of an exact match

When events and quotes do not coincide to the millisecond, an exact join returns nothing. For each row of the left table, pd.merge_asof() takes the last row of the right table whose key does not exceed the left value. Sort both tables by the key beforehand.

pythonthe trade at 09:00:00.050 is matched with the quote at .045
trades = pd.DataFrame({    "time": pd.to_datetime(        ["09:00:00.010", "09:00:00.050"],        format="%H:%M:%S.%f"),    "price": [182.1, 182.3],})quotes = pd.DataFrame({    "time": pd.to_datetime(        ["09:00:00.000", "09:00:00.045"],        format="%H:%M:%S.%f"),    "bid": [182.0, 182.2],})pd.merge_asof(trades, quotes, on="time")

The by parameter groups the keys: each stock gets the latest quote for that stock only. tolerance limits how stale a match may be; if the quote is older, the right-hand fields stay NaN.

pythontolerance drops quotes that are too old
pd.merge_asof(trades, quotes, on="time",              tolerance=pd.Timedelta("5ms"))# a quote that is too old: bid = NaN

Learn more

To find rows that were multiplied or lost after a join, see “Common errors and diagnostics”. Changing the shape of a table, from wide to long and back, is covered in “Reshaping: pivot, melt, stack”. For more on row labels and alignment, see “Series, DataFrame, Index and dtypes”; for working with dates as keys, see the time series section.

Section sources

the section is written from these pages

Reshaping: pivot, melt, stack

Reshaping moves a table between long format, where each row is one observation, and wide format, where the values of a variable are spread across columns. pivot and pivot_table turn long into wide; melt goes back.

Choose the layout to fit the task. Long format is for storing and appending data: a row carries a month, a city and a value. Wide format is for comparing cities side by side and building summaries: each city gets its own column. The format for storage and the format for a report differ, so you convert the table back and forth:

pivot and melt convert a table back and forth without losing data

pivot and pivot_table

pivot spreads the values of one column across new columns: index stays as the row labels, the unique values of columns become the column headers, and the values column fills the cells. The result is a pivot table:

pythonthe table used in all the examples
import pandas as pd sales = pd.DataFrame(    {        "month": ["2026-01", "2026-01", "2026-01",                  "2026-02", "2026-02", "2026-02"],        "city": ["Tashkent", "Samarkand", "Bukhara",                 "Tashkent", "Samarkand", "Bukhara"],        "amount": [1200, 450, 210, 980, 610, 190],    }) # from long to wide formatwide = sales.pivot(index="month", columns="city", values="amount")wide# city     Bukhara  Samarkand  Tashkent# month# 2026-01      210        450      1200# 2026-02      190        610       980

For summaries, pivot_table is more common: it aggregates values and can add totals. The main parameters:

ParameterWhat it doesDefault
valueswhich column to put in the cellsall the rest
indexwhat to keep as row labelsnone
columnswhose values become the columnsnone
aggfuncaggregation function: "mean", "sum", "count""mean"
fill_valuewhat to fill empty cells of the result withempty
marginsadd a row and a column of totalsFalse
margins_namename of the totals row and column"All"

margins=True appends a row and a column with totals for each group; margins_name sets their name. You can omit values, and the method then aggregates all suitable columns:

pythonpivot_table with totals
piv = sales.pivot_table(    values="amount", index="month", columns="city",    aggfunc="sum", margins=True, margins_name="total",)piv# city     Bukhara  Samarkand  Tashkent  total# month# 2026-01      210        450      1200   1860# 2026-02      190        610       980   1780# total        400       1060      2180   3640

melt: back to long format

melt turns a wide table back into a long one: id_vars are the anchor columns that stay as columns, and the method stacks the rest into two: var_name holds the variable name and value_name holds the value. Without value_vars, all columns except the anchors are unpivoted.

pythonback to long format
wide.reset_index().melt(    id_vars="month", var_name="city", value_name="amount")#     month       city  amount# 0  2026-01    Bukhara     210# 1  2026-02    Bukhara     190# 2  2026-01  Samarkand     450# 3  2026-02  Samarkand     610# 4  2026-01   Tashkent    1200# 5  2026-02   Tashkent     980

pivot and melt are reversible: reset the result’s index with reset_index() and you get the original long table. melt does not preserve row order, so sort the result if you need to.

stack and unstack

When a table is already pivoted, stack and unstack move levels between rows and columns. They are designed for hierarchical labels (MultiIndex): stack moves a column level into the row labels, and unstack does the opposite, by default the innermost level; the level parameter picks the one you need. After stack, you get a Series with a two-level index.

pythonstack: columns into row labels
st = wide.stack()st# month    city# 2026-01  Bukhara       210#          Samarkand     450#          Tashkent     1200# 2026-02  Bukhara       190#          Samarkand     610#          Tashkent      980# dtype: int64 st.unstack()  # back to wide

crosstab for contingency tables

pd.crosstab counts the frequencies of combinations of two variables, producing a contingency table. With a values column and an aggregation function, it becomes a summary, and normalize="index" converts the numbers to proportions within each row.

pythonanswer frequencies by platform
answers = pd.DataFrame(    {        "platform": ["desktop", "desktop", "mobile", "mobile"],        "answer": ["yes", "no", "yes", "no"],        "count": [312, 88, 410, 60],    })ct = pd.crosstab(    answers["platform"], answers["answer"],    values=answers["count"], aggfunc="sum",    margins=True, margins_name="total",)ct.rename_axis(columns=None)#           no  yes  total# platform# desktop     88  312    400# mobile      60  410    470# total      148  722    870

explode for a column of lists

explode unpacks a column of lists: each list element becomes a separate row with the same index label. ignore_index=True gives the result new labels starting from 0.

pythona list into separate rows
surveys = pd.DataFrame(    {        "city": ["Tashkent", "Samarkand"],        "tags": [["price", "internet"], ["price"]],    })surveys.explode("tags", ignore_index=True)#        city      tags# 0  Tashkent     price# 1  Tashkent  internet# 2  Samarkand     price

How to choose a tool

TaskTool
store and append observationslong format
compare variables side by sidepivot, if the combinations are unique
the same with repeats and totalspivot_table
turn a wide table into a long onemelt
move a level of labelsstack and unstack
frequencies of combinations of two variablescrosstab
a list of values into rowsexplode

A pivot table only rearranges the data; it is not a separate calculation. Its numbers are the same as grouping by the same keys would give. For details, see “Grouping: groupby”. For the SQL equivalent of pivoting, see the sql reference.

Section sources

the section is written from these pages

Dates and time series

pandas stores dates in the datetime64 type, and a time series is a table or Series whose row labels are dates. to_datetime turns strings into dates, .dt gives access to date parts, resample computes totals by day or month, and rolling computes moving values. The examples use this revenue table:

pythonexample used by all the code blocks below
import pandas as pd sales = pd.DataFrame({    "date": pd.to_datetime([        "2026-03-01", "2026-03-02",        "2026-03-04", "2026-03-05",    ]),    "revenue": [1200, 1450, 900, 1610],})

to_datetime: strings to dates

With no arguments, to_datetime parses ISO 8601 strings (2026-03-01, 2026-03-01 10:00) and similar ones. For a format such as day/month/year, pass the format explicitly: it is more reliable than automatic guessing and speeds up parsing of large tables.

pythonformat mismatch error
sales["date"] = pd.to_datetime(sales["date"])# without format: "2026-13-01" raises DateParseError (a ValueError subclass): month must be in 1..12 # a format mismatch gives a hint listing all the ways outpd.to_datetime(["15/03/2026"], format="%Y-%m-%d")# ValueError: time data "15/03/2026" doesn't match format "%Y-%m-%d"

The hint in the error message lists those ways out: set a common format, use format="ISO8601" for strings in different ISO variants, or format="mixed" for strings that are entirely heterogeneous. With errors="coerce", a bad value becomes the missing value NaT instead of raising an error, so one failure does not stop the parsing of the other rows.

pythoncoerce turns an invalid value into NaT
raw = pd.Series(["15/03/2026", "02/07/2026", "invalid"])pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce")# 0   2026-03-15# 1   2026-07-02# 2          NaT

The unit parameter parses epoch numbers: pd.to_datetime([1767225600], unit="s") gives 2026-01-01. As of pandas 3.1, the result type for numeric input no longer follows the unit; it uses microseconds. Series.dt.as_unit() returns the resolution you need.

Date parts with .dt

A column of dates has a .dt accessor. It returns date parts under the same names as Timestamp: year, month, day, hour, day_of_week (Monday is 0), days_in_month, quarter, day_name().

python
d = sales["date"]d.dt.day_of_week        # 6, 0, 2, 3d.dt.days_in_month      # 31, 31, 31, 31d.dt.day_name()         # Sunday, Monday, Wednesday, Thursday

A date index and slices

It is convenient to keep a time series with a date index (DatetimeIndex): rows can then be sliced by dates, and resample and rolling work directly on the index. Build the index with set_index or pd.date_range(start=…, periods=…, freq=…).

pythonslice bounds are inclusive
ts = sales.set_index("date")ts.loc["2026-03"]                       # all of Marchts.loc["2026-03-02":"2026-03-04"]       # two rows: 02 and 04 # a partial slice also works in a DataFramets.loc["2026-03", "revenue"]

A year such as “2026” and a month such as “2026-03” are slices too, and both bounds are inclusive. For a DataFrame, selecting one row by date works only through loc: df["2026-03-01"] is no longer supported. Time windows and partial slices expect a sorted index: a window on an unsorted one fails with index values must be monotonic, and a slice whose bound is not in the index fails with KeyError. Sort with ts.sort_index().

Time zones

Dates without a time zone are called naive: the type is datetime64[us]. tz_localize assigns a zone and tz_convert converts to another one: localise first, then convert. Localising attaches the offset without changing the clock time; converting shifts the clock time and preserves the moment in time.

pythonlocalise first, then convert
s = sales["date"]s.dt.tz_localize("Asia/Tashkent")# dtype: datetime64[us, Asia/Tashkent] s.dt.tz_localize("UTC").dt.tz_convert("Asia/Tashkent")# 2026-03-01 05:00+05:00 — 00:00 UTC is 05:00 in Tashkent
pythonutc=True converts everything to UTC
pd.to_datetime(["2026-03-01 09:00 +0500", "2026-03-01 12:00 +0300"])# ValueError: Mixed timezones detected. Pass utc=True … pd.to_datetime(    ["2026-03-01 09:00 +0500", "2026-03-01 12:00 +0300"],    utc=True,)# 2026-03-01 04:00+00:00, 2026-03-01 09:00+00:00

resample: totals by period

resample is grouping by time: it cuts the series into intervals by a frequency rule and computes an aggregate for each. It works on the date index or on a column named in on=; the frequency is a string, called an offset alias.

AliasIntervalInterval label
Dcalendar dayleft edge
Wweekright edge, Sunday
hhourleft edge
minminuteleft edge
ssecondleft edge
MEmonth endright edge
MSmonth startleft edge
QEquarter endright edge
YEyear endright edge
Bbusiness dayleft edge

Write a multiple as a number: "5min", "2h", "1ME". Any groupby aggregate computes the totals: sum, mean, count, agg with a list of functions.

pythonsum by month, mean by week
ts.resample("ME")["revenue"].sum()# 2026-03-31    5160 ts.resample("W")["revenue"].mean()# 2026-03-01    1200.0# 2026-03-08    1320.0

By default, an interval is labelled with its edge: for W and ME the labels are right edges, so the March total is labelled 2026-03-31. With label="left", the label is the left edge, and closed= moves the interval boundary to the other edge. The on= parameter computes by a column without touching the index:

pythona column instead of the index
sales.resample("ME", on="date")["revenue"].sum()# 2026-03-31    5160

rolling and expanding: moving values

A rolling window is an aggregate over the last n rows that moves along with them. rolling(3).mean() gives the mean of each three adjacent values; the first rows do not have enough values for a window, so they get NaN. The min_periods parameter relaxes this requirement: rolling(3, min_periods=1) also computes on incomplete windows.

pythonmin_periods also computes on incomplete windows
rev = ts["revenue"]rev.rolling(3).mean()# 2026-03-05    1183.33 — the mean of 1200, 1450 and 900 rev.rolling(3, min_periods=1).mean()# 1200.0, 1325.0, 1183.33, 1320.0

A window can also be set by time: rolling("3D") includes all rows within three days up to the current one. An expanding window grows: the aggregate covers all rows from the start to the current one. Related methods: shift(1) moves values down one row, which puts yesterday’s value next to today’s; diff() computes the difference from the previous row; and shift with freq="D" shifts the index dates themselves, leaving the data in place.

python
rev.rolling("3D").mean()# 1200.0, 1325.0, 1175.0, 1255.0 rev.expanding().mean()# 1200.0, 1325.0, 1183.33, 1290.0 rev.shift(1)# NaN, 1200, 1450, 900 — values of the previous rowrev.diff()# 250, -550, 710 — day over day

Learn more

For NaT and NaN gaps, see “Missing values”: empty intervals after resample are filled with ffill() and interpolate(). Selection by mask is covered in “Selecting and filtering”. Weighted and exponential windows (ewm) are in the pandas documentation. If you know SQL, resample mirrors GROUP BY on a computed period: see the sql reference, the section “Aggregate functions and GROUP BY”.

Section sources

the section is written from these pages

Common errors and diagnostics

Diagnosis starts with three questions: what are the column types (df.dtypes), how big is the table (df.shape), and what do the first rows look like (df.head()). Most unexpected pandas results come down to the wrong column type or the wrong row labels.

pythonthe first three checks
import pandas as pd df = pd.read_csv("data.csv")print(df.dtypes)  # the type of each columnprint(df.shape)   # rows and columnsdf.head()         # eyeball the first rows

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().

Cause: where Python needs a single boolean, in an if or with the and and or operators, you have passed a Series of many values, and the truth value of a Series is not defined. For row-by-row conditions, use & and |, which produce a mask. To get a single value for the whole Series, use any(), all() and a.empty.

python
s = pd.Series([1, 5, 10]) # wrong: s > 0 and s < 5 — and needs a single bool# right: bitwise operators produce a masks[(s > 0) & (s < 5)]

ValueError: cannot reindex on an axis with duplicate labels

Cause: rows or columns have repeated labels, and a method that rebuilds the index, such as reindex() or alignment in arithmetic, cannot tell which of the rows labelled "b" to use. Find duplicates with index.is_unique and index.duplicated(); remove them and the error goes away. Selection by a duplicated label also behaves differently: with two columns named A, df["A"] returns a DataFrame, not a Series.

pythondiagnosis and fix
s = pd.Series([0, 1, 2], index=["a", "b", "b"])print(s.index.is_unique)     # Falseprint(s.index.duplicated())  # [False False True] # drop duplicates, keeping the first occurrences = s[~s.index.duplicated()]

To stop duplicates from appearing further down the pipeline, forbid them with the set_flags(allows_duplicate_labels=False) flag: any operation that introduces a duplicate fails with DuplicateLabelError, and the flag rejects a table that already has duplicates.

TypeError: boolean value of NA is ambiguous

Cause: a missing value pd.NA has reached a condition. A missing value means “unknown”, so its truth value is undefined and it cannot be turned into a boolean in an if. Replace it with False using fillna(False), test for it with isna(), and use &, | and ~ instead of and, or and not with nullable masks: they work element by element and follow Kleene logic, so True | NA gives True and False & NA gives False.

python
mask = pd.Series([True, pd.NA, False], dtype="boolean") # wrong: if mask[1]: — TypeError, the scalar pd.NA in a condition# right: replace the missing value with Falsemask = mask.fillna(False)if mask.any():    ...

ChainedAssignmentError on assignment

Cause: a value is written through two selections in a row, such as df["a"][0] = 1. With Copy-on-Write, such an assignment changes a temporary copy rather than the original table, so pandas accompanies it with a ChainedAssignmentError warning. Select the row and the column in a single loc or iloc call.

python
df = pd.DataFrame({"a": [1, 2, 3], "b": [0, 0, 0]}) # wrong: df["a"][0] = 10# right: a single loc operationdf.loc[0, "a"] = 10 # a mask on another columndf.loc[df["b"] == 0, "a"] = 0

KeyError when selecting a column or label

Cause: there is no label with that name, and loc raises KeyError for any label that is not in the index. Common culprits are leading or trailing spaces and letter case, since " Amount" and "amount" are different columns, and using a position where a label is needed: df.loc[0] looks for the label 0, not the first row. The expression "amount" in df.columns checks for a column without raising an error; select by position with iloc.

python
print(df.columns.tolist())           # names as they areprint([repr(c) for c in df.columns])  # spaces become visible # strip spaces from the namesdf.columns = df.columns.str.strip()

A numeric column read as strings

Symptom: df.dtypes shows str for a numeric column, sorting is textual (“10” comes before “9”), and arithmetic fails. Cause: the file contains spaces, a currency symbol, or a comma as the decimal separator. to_numeric() with errors="coerce" restores the numbers: non-numeric values become missing values, and df[df["price"].isna()] shows them.

python
# after readingdf["price"] = pd.to_numeric(df["price"], errors="coerce") # or right when reading, if the separator is non-standarddf = pd.read_csv("data.csv", decimal=",", thousands=" ")

Dates are not recognised

Symptom: the date column stayed as strings of type str instead of datetime64. Causes: the format is not ISO (“01/02/2026”), the dates are split across several columns, or parse_dates is not set. The reliable way is to specify the format explicitly; values that do not fit become missing values with errors="coerce".

python
df = pd.read_csv(    "data.csv",    parse_dates=["day"],    date_format={"day": "%d/%m/%Y"},)# if the file has already been readdf["day"] = pd.to_datetime(    df["day"], format="%d/%m/%Y", errors="coerce",)

More rows than expected after merge

Symptom: there were 10,000 rows, and now there are 14,000. Cause: the join key repeats in one of the tables, and each pair of matching rows produces a new row in the result. Duplicate keys multiply rows, and on large tables this ends in running out of memory. Check left["id"].is_unique before the join, and make merge() check the same thing with validate: many_to_one fails with MergeError if the keys on the right are not unique, before the result grows. The other modes are one_to_one, one_to_many and many_to_many.

python
orders.merge(    customers, on="id", validate="many_to_one",)

Running out of memory on a large CSV

Symptom: reading eats all the memory or the process is killed. Cause: pandas keeps the whole table in memory, and the default types are wasteful: counters as int64, repetitive strings without compression. The cure is to shrink the data: do not read unneeded columns, set compact types up front, and process the file in chunks.

pythoncutting memory use in three steps
# 1. do not read unneeded columnsdf = pd.read_csv("big.csv", usecols=["id", "price"]) # 2. set the types when readingdf = pd.read_csv(    "big.csv",    usecols=["id", "price", "city"],    dtype={"id": "uint32", "city": "category"},) # 3. process in chunksfor chunk in pd.read_csv("big.csv", chunksize=100_000):    process(chunk)

df.info(memory_usage="deep") shows how much memory the table takes and which column uses the most.

SymptomCauseWhat to do
if or and with a Series failsthe truth value of a Series is undefined& and |, and any(), all(), a.empty for a single result
cannot reindex on an axis with duplicate labelsduplicate row or column labelscheck index.is_unique, remove duplicates or forbid them with the flag
boolean value of NA is ambiguousa missing value pd.NA reached a conditionfillna(False), & instead of and, test with isna()
ChainedAssignmentError on assignmenttwo selections in a row change a copyassign with a single loc or iloc
KeyError on a column name or labelspaces, letter case, label not in the indexdf.columns.tolist(), str.strip(), check with in
a numeric column behaves like texttype str because of spaces and symbolsto_numeric(..., errors="coerce"), dtype in read_csv
dates stayed as stringsformat is not ISO, no parse_datesparse_dates and date_format, to_datetime(format=…)
more rows after merge than beforethe join key is not uniquecheck is_unique, set validate
MemoryError or the process is killedthe table does not fit in memoryusecols, compact dtype, chunksize

Section sources

the section is written from these pages

Versions and what’s new

This reference covers pandas 3.1; the latest release is 3.1.1, published on 4 November 2026. A version number has three parts: major, minor and patch. Breaking changes arrive only in major releases; deprecations are announced in advance, in minor ones.

pandas follows a loose form of SemVer: the project’s policies page sets the rules for compatibility and deprecations. A minor release (3.0 → 3.1) adds features and announces deprecations; a patch release (3.1.0 → 3.1.1) fixes bugs and announces no new deprecations. A deprecated feature keeps working in its branch, with a warning, until the next major release.

BranchFirst releaseLatest release
3.13.1.0 — 22 October 20263.1.1 — 4 November 2026
3.03.0.0 — 21 January 20263.0.6 — 17 September 2026
2.32.3.0 — 4 June 20252.3.3 — 29 September 2025

The project publishes no support periods: pandas is open source and maintained by volunteers. The table shows that the previous branch stops receiving patches around the time the next minor release appears, so update within your branch regularly. pandas has supported Python 3.15 since release 3.0.6; the last release of the 2.3 branch (2.3.3) was the first to support Python 3.14.

What’s new in 3.1

The main changes in 3.1.0 (October 2026) compared with 3.0:

  • The DataFrame.select method returns a table of the listed columns; columns can be computed with pandas.col() expressions and functions. See the section “Selecting and filtering”.
  • filter selects rows by a mask through the new cond parameter; passing the mask positionally, as before, is no longer allowed and raises a UserWarning. See the section “Selecting and filtering”.
  • CSV reading with the c engine is two to three times faster, and large local files are read in parallel on several cores: an uncompressed file of 5 MB or more (without a header), unless parameters such as chunksize that need the whole file are set. The mode.max_threads option limits the number of threads; by default it is at most six. See the section “Reading and writing data”.
  • NumPy 2.0.2 or newer is required: support for NumPy 1.x has ended.
  • read_csv with dtype="category" creates numeric and boolean categories, not string ones, in all engines.

Release 3.1.1 followed two weeks later with only regression and bug fixes, among them corruption of missing date values in DataFrame.astype with dtype_backend="pyarrow" and a faulty file write when a path object with a write method was mistaken for an open file.

What changed in 3.0

If you are moving from the 2.x branch, the main points of 3.0 (January 2026) are:

  • Copy-on-Write: every selection behaves as a copy, chained assignment no longer works and raises ChainedAssignmentError; SettingWithCopyWarning has been removed. See the section “Copy-on-Write: a selection is a copy” in “Series, DataFrame, Index and types”.
  • The string data type str is the default instead of object (backed by PyArrow, if installed). See the section “Column types”.
  • Much that was deprecated in the 2.x branches has been removed: the method and limit parameters of replace, the delim_whitespace parameter of read_csv (use sep=r'\s+'), the frequency aliases M, Q, Y in favour of ME, QE, YE, and the DataFrame.first and DataFrame.last methods.
  • The minimum Python version is now 3.11; time zones work through the standard zoneinfo module instead of pytz.

Deprecated and removed

Deprecations are announced in minor releases and removed in major ones: anything announced in 3.1 keeps working in its branch, with a warning, until 4.0. Under the three-stage PDEP-17 policy, a new deprecation first raises PandasDeprecationWarning, which Python hides by default outside the main module; in the last minor release before a major one the warning is switched to PandasFutureWarning and becomes visible to everyone. Deprecations that will be removed in 4.0 arrive as Pandas4Warning. Here is what 3.1 announced:

  • The inplace parameter of methods that do not actually modify data in place: drop, rename, rename_axis, reset_index, set_index, dropna, drop_duplicates, sort_values, sort_index, eval, query. Copy-on-Write makes it redundant: assign the result instead, as in df = df.reset_index().
  • .values on time zone-aware, period and interval types returns a NumPy array that loses some of the data; 4.0 will return an ExtensionArray. Use .array for an ExtensionArray and .to_numpy() for NumPy.
  • The mode.chained_assignment option is deprecated: since 3.0 it has no effect, and chained assignment raises ChainedAssignmentError.
  • The lsuffix and rsuffix parameters of DataFrame.join; use suffixes instead, as in merge.
  • The default date_format='epoch' in to_json: the warning is now raised for dates in the index and column headers too, not only in values.

Other items in 3.1: the default value of check_freq in the pandas.testing functions (assert_index_equal and its neighbours) is deprecated, so pass it explicitly; reading .xlsx with python-calamine installed warns about a future change of the default engine from openpyxl to calamine.

Removals happen at major-release boundaries: 3.0 removed the items listed above and much more from the 2.x branches. The 3.1 release notes contain no separate list of removals.

How to upgrade

Within a branch, upgrading comes down to a single pip command; there is no risk to your data, but check your code for deprecation warnings.

bashin the project environment
source .venv/bin/activatepip install "pandas==3.1.1"python -c "import pandas; print(pandas.__version__)"

To move between branches, first upgrade to the latest release of your current branch and get your code running without warnings, then upgrade and read the notes for the next branch: in 3.0, the frequency aliases and parameters removed from the 2.x branches stop working, and chained assignments break.

bashupgrading from 2.x to 3.1
pip install "pandas==2.3.*"# show hidden deprecation warnings while checking your codepython -W default::DeprecationWarning your_script.pypip install "pandas==3.1.*"

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “pandas” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61