The pandas Python library is a package for working with tabular and labeled data: you load a file into a DataFrame, then filter, summarize, clean and save it with short method calls. Install it with python -m pip install pandas, load data with pd.read_csv("file.csv"), and the sections below show the operations you will use most.
What the pandas library is
The pandas documentation describes it as a Python package that provides fast, flexible and expressive data structures designed to make working with relational or labeled data easy and intuitive. It is built on NumPy, and the license is BSD 3-Clause. Two structures do most of the work:
| Structure | Dimensions | What it is |
|---|---|---|
Series | 1 | A labeled array where every value has the same type. One column of a table. |
DataFrame | 2 | A labeled table. Columns can hold different types, and you can add or remove columns. |
Think of a DataFrame as a spreadsheet sheet or a database table that you control with code. The overview page lists the jobs pandas is meant for: handling missing data, grouping with split-apply-combine operations, merging and joining data sets, time series work such as date ranges and moving windows, and reading and writing flat files, Excel files and databases.
The library is useful once a spreadsheet gets too big or too repetitive to click through. A script that cleans a file can be run again on next month's export, and every step is written down.
Install pandas and import it
Install into a virtual environment so it does not touch your system Python:
python -m pip install pandas
On many Linux distributions a system-wide install fails; Fix pip "error: externally-managed-environment" explains why and what to do. Then import it. The convention is the alias pd, which a separate article covers in detail:import pandas as pd: What It Does and How to Fix Errors.
import pandas as pd
print(pd.__version__)
The version printed depends on what you installed. If you plan to read or write Excel files, you need an extra package; see pip install pandas openpyxl: Read and Write Excel Files.
How to create a DataFrame
You can build a DataFrame from a dictionary where each key is a column name and each list holds that column's values. The example below is a small made-up sales table. Note the None in units, which stands for a missing value.
import pandas as pd
orders = pd.DataFrame(
{
"region": ["north", "south", "north", "east", "south", "north"],
"product": ["pen", "pen", "ink", "pen", "ink", "pen"],
"units": [10, 4, 3, None, 8, 6],
"price": [1.5, 1.5, 7.0, 1.5, 7.0, 1.5],
}
)
print(orders)
Example output:
region product units price
0 north pen 10.0 1.5
1 south pen 4.0 1.5
2 north ink 3.0 7.0
3 east pen NaN 1.5
4 south ink 8.0 7.0
5 north pen 6.0 1.5
The numbers 0 to 5 on the left are the row labels, called the index. Notice that units printed as 10.0, not 10. The column holds a missing value, and plain NumPy integers cannot, so pandas stored the column as floating point numbers with NaN in the gap.
Most of the time you will not type data in. You will read it from a file:
orders = pd.read_csv("orders.csv")
The documentation's tutorials load their sample data this way, and orders.csv here stands for any CSV in your working folder.
How to select columns and filter rows
Square brackets with a column name return a Series. A list of names inside the brackets returns a DataFrame:
orders["units"] # a Series
orders[["region", "units"]] # a DataFrame with two columns
The pandas tutorial points out that the inner brackets are a plain Python list and the outer brackets do the selecting. To filter rows, put a condition inside the brackets. Only rows where it is true are kept:
orders[orders["units"] > 5]
With the table above, this returns rows 0, 4 and 5, which have 10, 8 and 6 units. The row with the missing value is dropped, because a comparison with NaN is false.
Two rules trip up newcomers. First, combine conditions with & for and, and | for or, and put each condition in parentheses. The Python keywords and and or do not work on Series. Second, once you select rows and columns together, use loc or iloc:
orders.loc[(orders["region"] == "north") & (orders["units"] > 5), "product"]
orders.iloc[0:3, 1:3]
loc selects by label, including conditions. iloc selects by integer position, and its end position is exclusive, like a Python slice. The second line returns rows at positions 0 to 2 and columns at positions 1 and 2. In both, the part before the comma picks rows and the part after picks columns. To keep rows from a list of allowed values, use isin, for example orders[orders["region"].isin(["north", "east"])].
How to add a column and group data
Arithmetic on columns works element by element, so adding a new column takes one line:
orders["revenue"] = orders["units"] * orders["price"]
The result is 15.0, 6.0, 21.0, NaN, 56.0 and 9.0, because NaN times anything is NaN. To total revenue per region, use groupby. The pandas docs describe it as split-apply-combine: split the rows into groups, apply a function to each group, and combine the results into one structure.
orders.groupby("region")["revenue"].sum()
Example output:
region
east 0.0
north 45.0
south 62.0
Name: revenue, dtype: float64
Check the arithmetic: north is 15 + 21 + 9 = 45, and south is 6 + 56 = 62. East has only the missing row, and the missing-data documentation says a sum of all-missing values is 0.0, so it shows 0.0 instead of a gap. That is easy to misread as "no revenue", so know which one you mean.
You can pass a list to group by several columns, as in groupby(["region", "product"]). For quick counts of each category, value_counts does the grouping and counting in one call:
orders["region"].value_counts()
That returns 3 for north, 2 for south and 1 for east. Related to this, the docs note that count excludes missing values while size counts every row in the group.
For a fast overview of numeric columns, call describe:
orders[["units", "price"]].describe()
It returns the count, mean, standard deviation, minimum, quartiles and maximum of each column. Statistics skip missing values by default, so the count row for units would be 5, not 6. The docs show the same effect on their Titanic data, where the age column has 714 values in 891 rows.
How to handle missing values
Use isna() or notna() to find them. Do not compare with ==: in Python and NumPy, np.nan == np.nan is False. Then pick one of two strategies.
- Drop them.
orders.dropna()removes every row that contains a missing value. Passaxis=1to drop columns instead. - Fill them.
orders["units"].fillna(0)replaces gaps with a value.fillnaalso accepts a dictionary for per-column values, andffill()andbfill()copy the previous or next value into a gap.
Neither choice is neutral. Filling units with 0 says that nothing was sold, which may not be true. Dropping the row loses its other columns. Decide per column, and write the reason in a comment.
Both methods return a new object and leave orders unchanged, so assign the result to a variable if you want to keep it:
clean = orders.dropna()
How to save the result
Write a DataFrame back to a CSV file with to_csv:
clean.to_csv("orders_clean.csv", index=False)
By default index=True, which writes the row labels as an extra first column. That extra column is rarely wanted, so pass index=False. If you leave out the path, to_csv() returns the CSV text as a string instead of writing a file. Everything after the path is keyword-only, so write sep=";", not a bare positional argument.
If it still fails
ModuleNotFoundError: No module named 'pandas'. The Python running your script is not the one you installed into. Runpython -m pip install pandasusing the same interpreter and virtual environment.KeyErroron a column name. Names must match exactly, including capitals and trailing spaces. Printorders.columnsto see the real names.ValueError: The truth value of a Series is ambiguous. You usedand,oror a bare Series in anif. Use&and|with parentheses around each condition.- Numbers show up as text. If one stray value such as
"n/a"sits in a numeric column, pandas reads the whole column as strings. Checkorders.dtypes, then fix the value in the source file or load the file withna_valuesset.
Frequently asked questions
- Is the pandas Python library free to use?
- Yes. The pandas documentation states that pandas is released under the BSD 3-Clause License, which allows commercial use. You install it with pip and do not pay for it or register for anything.
- What is the difference between pandas and NumPy?
- NumPy provides fast arrays of numbers that all share one type. pandas is built on NumPy and adds labels: a Series is a labeled one-dimensional array, and a DataFrame is a labeled table whose columns can hold different types. Use pandas when your data has column names, mixed types or missing values.
- Does pandas change my original file when I edit a DataFrame?
- No. A DataFrame lives in memory. Reading a CSV with read_csv copies its contents into the DataFrame, and nothing is written back until you call a method such as to_csv. Be careful that to_csv overwrites an existing file at the same path by default.
- Why does my integer column turn into floats after loading?
- NumPy integer types cannot store a missing value, so pandas converts a column that contains missing entries to float64 and marks them as NaN. The pandas docs describe nullable dtypes such as Int64, which use pd.NA instead and keep whole numbers as integers.