Coding

import pandas as pd: What It Does and How to Fix Errors

import pandas as pd loads the pandas library and gives it the short name pd, so you can write pd.DataFrame and pd.read_csv instead of the full pandas. prefix. If the line raises ModuleNotFoundError: No module named 'pandas', pandas is not installed in the Python you are running; fix it with python -m pip install pandas.

What import pandas as pd means

The statement has two parts. import pandas loads the package so its functions and classes become available. as pd binds the loaded package to the name pd in your script. After this line, pd and pandas would be the same thing, except that only pd exists as a name in your code.

import pandas as pd

print(pd.__version__)

That prints the installed pandas version, which is a quick way to confirm the import worked. The output depends on what you have installed.

The alias is a convention, not a requirement. The pandas documentation puts it this way: the community agreed alias for pandas is pd, so loading pandas as pd is assumed standard practice for all of the pandas documentation. Every example in the official docs starts from it, which is the practical reason to keep it. Code you copy will work as written, and anyone reading yours will know what pd refers to.

Install pandas first

An import only loads something that is already there. It does not download anything. The pandas installation page gives the command for pip users:

pip install pandas

I recommend the longer form, which guarantees that pip belongs to the same interpreter that will run your script:

python -m pip install pandas

On Windows, py -m pip install pandas does the same. The pandas page also recommends installing and running pandas from a virtual environment, for example one made with the standard library's venv. A virtual environment keeps the install out of your system Python and avoids the externally-managed-environment error on many Linux distributions; see Fix pip "error: externally-managed-environment" if you hit it.

To check which pandas, if any, a given interpreter can see:

python -m pip show pandas

If pip prints a name and version, the package is installed for that interpreter. If it reports that the package was not found, the import will fail too.

Your first DataFrame

The central object in pandas is the DataFrame. The pandas documentation describes it as a 2-dimensional data structure that can store data of different types, including characters, integers, floating point values and categorical data, in columns. It compares it to a spreadsheet, a SQL table or the data.frame in R.

The simplest way to make one is from a dictionary of lists. The documentation explains that the dictionary keys become the column headers, and the values in each list become the columns:

import pandas as pd

df = pd.DataFrame(
    {
        "Name": [
            "Braund, Mr. Owen Harris",
            "Allen, Mr. William Henry",
            "Bonnell, Miss Elizabeth",
        ],
        "Age": [22, 35, 58],
        "Sex": ["male", "male", "female"],
    }
)
print(df)

Example output, from the pandas getting-started tutorial:

                       Name  Age     Sex
0   Braund, Mr. Owen Harris   22    male
1  Allen, Mr. William Henry   35    male
2   Bonnell, Miss Elizabeth   58  female

The numbers on the left (0, 1, 2) are the row labels, called the index. pandas adds them for you unless you supply your own.

DataFrame versus Series

Select one column and you get a Series. According to the pandas documentation, a Series has no column labels, because it is just a single column of a DataFrame, but it does have row labels. You can also build one directly:

ages = pd.Series([22, 35, 58], name="Age")
print(ages)

Example output:

0    22
1    35
2    58
Name: Age, dtype: int64

Use df["Age"] to pull the same column out of the DataFrame above. The last line of the output, dtype: int64, tells you the type pandas chose for the values.

Read a CSV file with pd.read_csv

Most real work starts from a file instead of a typed-in dictionary. pd.read_csv reads a comma-separated file into a DataFrame:

import pandas as pd

df = pd.read_csv("sales.csv")
print(df.head())

Here sales.csv stands for any CSV in your current folder. The documentation says the first argument accepts a string path, including URLs with schemes such as http, ftp, s3, gs and file, as well as any path object or file-like object. df.head() returns the first rows of the DataFrame. Its default is n=5, and df.head(3) returns the first three. If n is larger than the number of rows, you get all rows.

A few read_csv defaults and options are worth knowing from the start:

OptionDefaultWhat it does
sep','The delimiter. Use sep=";" for semicolon-separated files, or sep="\t" for tab-separated ones.
header'infer'Equivalent to header=0 when you pass no names, so the first line becomes the column names. Pass header=None if the file has no header row.
usecolsNoneReads only the listed columns, by name or position. The docs note that element order is ignored.
nrowsall rowsReads only this many data rows, excluding the header. Handy for peeking at a large file.

For example, to look at only two columns of the first 100 data rows:

df = pd.read_csv("sales.csv", usecols=["date", "total"], nrows=100)

The column names date and total must exist in your file's header, or pandas raises an error naming the missing columns. Reading Excel files needs an extra library; that is covered in pip install pandas openpyxl: Read and Write Excel Files.

If it still fails

  • ModuleNotFoundError: No module named 'pandas'. The interpreter running the script is not the one pip installed into. This is common when an editor uses one Python and your terminal uses another. Run python -m pip install pandas with the same python you use to run the script, and activate your virtual environment before both steps. In VS Code, the interpreter shown in the bottom-right corner is the one used for the Run button.
  • NameError: name 'pd' is not defined. The import line is missing or runs after the line that uses pd. Put import pandas as pd at the top of the file. In a notebook, run the cell that contains it first, and run it again after restarting the kernel.
  • AttributeError: module 'pandas' has no attribute 'DataFrame'. This usually means Python found a different file called pandas.py, or a folder named pandas, next to your script before it found the real package. Rename your file, and delete any __pycache__ folder it left behind. Check where the module came from with print(pd.__file__); it should point into site-packages.
  • Pip cannot find a matching version. The installed Python may be too old for the current pandas release. Run python --version and compare it with the Python requirement on the pandas PyPI page, or use a newer interpreter in a fresh virtual environment.
  • A pip install into several environments. If you are unsure which environment is active, python -c "import sys; print(sys.executable)" prints the path of the interpreter in use. Install with that exact path: "<that path>" -m pip install pandas.

Pinning pandas for a project is easier with a requirements file; the format is explained in pip install requirements.txt: How It Works and How to Fix Errors.

Frequently asked questions

Do I have to write import pandas as pd?
No. import pandas works too, and then you write pandas.DataFrame instead of pd.DataFrame. The alias is a convention. The pandas documentation says the community agreed on pd as the alias and treats it as standard practice throughout its docs, so following it makes your code match almost every tutorial and answer you will read.
Can I use a different alias, such as import pandas as p?
Python allows any valid name after as. It will run, but other people reading your code, and code you copy from the pandas docs, will expect pd. Using a different alias also means copied examples fail with NameError: name 'pd' is not defined until you rename every pd.
Does import pandas as pd install pandas?
No. An import statement only loads a package that is already installed in the Python environment you are running. If pandas is missing you get ModuleNotFoundError, and the fix is to install it with python -m pip install pandas into that same environment.
What is the difference between a DataFrame and a Series?
A DataFrame is a 2-dimensional table whose columns can hold different data types. A Series is a single column. The pandas docs say that selecting one column of a DataFrame returns a Series, which has row labels but no column labels.

Sources