pandas

Also known as: pandas library

On this page 7

pandas is an open-source Python library that provides fast, flexible, labeled data structures, chiefly the DataFrame and the Series, for working with tabular and time-indexed data. In data processing, it serves as the everyday workbench for loading, cleaning, transforming, aggregating and exporting datasets that fit in the memory of a single machine.

Wes McKinney started the project in 2008 for quantitative financial analysis, and it is now maintained by a community under the NumFOCUS umbrella. The name derives from panel data, an econometrics term for multidimensional observations over time. The pandas library builds on NumPy arrays and, since version 2.0, can also use Apache Arrow as a storage backend.

How the DataFrame and Series structures work

A Series is a one-dimensional array of values paired with an index of labels, and a DataFrame is a two-dimensional collection of Series that share a common row index. Each column has a single dtype, such as int64, float64, datetime64[ns], category or string, while different columns can hold different types.

The defining feature is automatic index alignment. When two Series are added, pandas matches values by label rather than by position, inserting missing values where labels do not overlap. This behavior prevents silent misalignment errors common in plain arrays, but it surprises users who expect positional arithmetic.

The following table lists the core objects and the role each plays.

ObjectDimensionsTypical use
SeriesOne labeled columnA single variable or time series
DataFrameRows and named columnsA table loaded from CSV or SQL
IndexImmutable row or column labelsAlignment, lookup and joins
MultiIndexHierarchical labelsGrouped or panel-style data
GroupByDeferred grouping objectSplit-apply-combine aggregation
Core pandas data structures

Common data processing operations

Most pandas work follows a read, clean, transform, aggregate and write pattern. The library offers readers and writers for CSV, Excel, JSON, Parquet, SQL databases and many other formats, together with a large set of vectorized methods that operate on whole columns at once.

TaskKey methodsNotes
Loading dataread_csv, read_parquet, read_sqlSet dtypes early to save memory
Selecting rows and columnsloc, iloc, queryloc uses labels, iloc uses positions
Handling missing dataisna, fillna, dropnaSupports imputation and filtering
Removing duplicatesduplicated, drop_duplicatesBasic deduplication by key columns
Aggregatinggroupby, agg, pivot_tableImplements split-apply-combine
Combining tablesmerge, join, concatSQL-style joins on keys or index
Reshapingmelt, pivot, stackConverts between long and wide formats
Frequent tasks and the methods that perform them

Time-series support is a historic strength: date parsing, resampling, rolling windows and time zone conversion are built in. Calling resample on a datetime index can convert per-second sensor readings into hourly averages in a single line, which is why pandas remains common in finance, operations and scientific analysis.

Performance, memory and the Arrow backend

pandas is fast when code is vectorized and slow when it loops through rows in Python. Operations such as column arithmetic, boolean filtering and grouped aggregation run in optimized C and NumPy routines, whereas iterrows or row-wise apply invoke the Python interpreter for every row and can be tens to hundreds of times slower.

Memory is the practical ceiling. A DataFrame usually needs several times the size of the source file in RAM, because text columns stored as Python objects carry heavy overhead and many operations create intermediate copies. Converting repetitive strings to the category dtype, downcasting numeric types and reading only the needed columns can reduce memory use substantially.

Version 2.0 introduced optional PyArrow-backed dtypes, which store strings and nullable values more compactly and speed up Parquet input and output. The Copy-on-Write model, made the default in pandas 3.0, makes copying behavior predictable and removes the long-standing SettingWithCopyWarning confusion.

Several libraries share the DataFrame concept but target different data sizes and execution models. Choosing among them depends on whether the data fits in memory, whether parallel or distributed execution is needed and how much existing pandas code must be reused.

ToolExecution modelBest fit
pandasEager, single-threaded, in memoryInteractive analysis up to a few gigabytes
NumPyEager arrays without labelsNumerical computation on homogeneous arrays
DaskLazy, parallel, partitioned pandasLarger-than-memory data with pandas syntax
Apache SparkDistributed cluster engineTerabyte-scale batch processing
PolarsMultithreaded, lazy or eager, Arrow-basedFaster single-machine pipelines
pandas and neighboring DataFrame tools

pandas remains the de facto interchange format of the Python data ecosystem: plotting libraries, scikit-learn, statistical packages and notebook tools all accept DataFrames directly. That ecosystem position often outweighs raw speed differences for exploratory and medium-scale work.

Limitations and common mistakes

The library is powerful but has sharp edges that cause subtle bugs. Many of them stem from implicit type conversion, index behavior and chained operations whose results depend on whether pandas returned a view or a copy.

  • Chained assignment such as df[df.a > 0]['b'] = 1 may modify a temporary copy instead of the original; use a single loc call.
  • Silent type upcasting turns an integer column into floats when a missing value appears, unless nullable dtypes such as Int64 are used.
  • Ambiguous date parsing can swap day and month; pass an explicit format argument.
  • Unintended many-to-many merges multiply rows; the validate argument of merge catches this early.
  • Row-wise loops destroy performance; prefer vectorized expressions or numpy.where.

Finally, pandas is not a database. It offers no transactions, concurrent access control or persistent indexes, so production pipelines usually treat it as one processing step between durable storage layers rather than as the system of record.

Explained without jargon

pandas is a free toolkit for the Python programming language. It lets people work with tables of data in code, much like a spreadsheet. It is faster, though, and every step can be repeated.

Imagine a spreadsheet that opens a million rows without freezing. It fixes messy entries with one command. It combines two lists by a shared customer number and totals sales by month. pandas does exactly those jobs. Because every step is written down as code, the same cleanup can be rerun tomorrow on new data.

Its main limit is size: it works best when the data fits in a computer’s memory.

A typical use case

An online retailer’s analytics team receives daily order exports of about 2 million rows from its shop platform as CSV files. An analyst writes a pandas script that reads only the 12 columns needed, converts order dates with an explicit format and stores product categories as the category dtype, which cuts memory use from roughly 3 GB to under 1 GB.

The script removes duplicate order lines, fills missing shipping regions from a customer table using merge, and flags refunds. A groupby on week and category then produces revenue, order count and average basket size, and the result is written to Parquet for the reporting dashboard.

The whole pipeline runs in under two minutes on a laptop each morning, replacing a manual spreadsheet process that previously took an analyst half a day and occasionally produced inconsistent totals.