Skip to main content

Data analysis · Beginner · 16 min

Read Excel, CSV and Parquet files into pandas correctly

By Padding · Updated 18 Nov 2026
python:3.15-slim (Debian 13) · Python 3.15 · pandas 3.1.1 · openpyxl 3.1.5 · pyarrow 26.0.1

You will load a semicolon-separated CSV with the wrong encoding, a multi-sheet Excel workbook whose headers start on row 4 and a Parquet file into pandas 3.1 with the right types, leading zeros and dates intact, reading only the columns you need.

On this page

Most data problems start at the moment a file is loaded. pandas guesses what each column is, and a wrong guess is quiet: a customer ID of 00042 becomes the number 42, a balance of 1.250,50 is read as text, and a date stays a string you cannot sort by month. By the time you notice, the leading zeros are gone.

In this tutorial you create three realistic files and load each one properly: a CSV exported from a spreadsheet set to a French locale, an Excel workbook with one sheet per shop branch and a title block above the headers, and a Parquet file. You tell pandas the encoding, separators, column types and date format up front, so the table is right from the first line of your analysis. Cleaning messy values after loading is a separate job, covered in clean a CSV file with pandas.

Everything runs in a throwaway folder, ~/read-files-demo, which you can delete at the end.

Step 1 · Create the project and the sample files

Make the folder and add pandas, openpyxl (the library pandas uses to read .xlsx files) and pyarrow (the library behind Parquet). Each range allows patch releases only:

Bash
mkdir -p ~/read-files-demo
cd ~/read-files-demo
uv init --no-package
uv add "pandas>=3.1,<3.2" "openpyxl>=3.1,<3.2" "pyarrow>=26.0,<27"
uv run python -c "import pandas, openpyxl, pyarrow; print(pandas.__version__, openpyxl.__version__, pyarrow.__version__)"

Now write make_files.py. It produces the two awkward files you will read in the next steps. customers.csv is what a spreadsheet on Windows set to a French or German locale typically saves: semicolons between fields, a comma as the decimal mark, a dot between thousands, and text in the Windows cp1252 encoding rather than UTF-8. sales.xlsx has three sheets, and each starts with two title lines and a blank row, so the real headers are on row 4.

Bash
cat > make_files.py <<'PY'
from datetime import date

from openpyxl import Workbook

# A CSV saved by a spreadsheet set to a French or German locale on Windows:
# semicolons between fields, commas in decimals, dots in thousands, cp1252 text.
rows = [
    "customer_id;name;city;phone;signup_date;balance",
    "00042;Adaeze Okafor;Lagos;08031234567;17/03/2026;1.250,50",
    "00107;Aïcha Diallo;Dakar;0771234567;02/04/2026;980,00",
    "00315;Kofi Mensah;Accra;0244123456;11/04/2026;12.400,75",
    "01020;Hélène Mbarga;Douala;0699123456;05/05/2026;310,20",
    "01203;João Tembe;Maputo;0841234567;30/05/2026;2.075,00",
    "02210;Wanjiru Kamau;Nairobi;0712345678;09/06/2026;45,90",
]
with open("customers.csv", "w", encoding="cp1252", newline="") as f:
    f.write("\r\n".join(rows) + "\r\n")

# A workbook with one sheet per branch. Each sheet has a title block,
# so the real column headers start on row 4.
orders = {
    "Lagos": [("L-0001", date(2026, 10, 1), "Rice 5kg", 3, 9500.0),
              ("L-0002", date(2026, 10, 2), "Palm oil 1L", 5, 2800.0),
              ("L-0003", date(2026, 10, 4), "Rice 5kg", 1, 9500.0)],
    "Nairobi": [("N-0001", date(2026, 10, 1), "Maize flour 2kg", 4, 210.0),
                ("N-0002", date(2026, 10, 3), "Tea 500g", 2, 380.0)],
    "Accra": [("A-0001", date(2026, 10, 2), "Gari 1kg", 6, 25.0),
              ("A-0002", date(2026, 10, 5), "Tomato paste", 10, 8.5)],
}
wb = Workbook()
wb.remove(wb.active)
for branch, lines in orders.items():
    ws = wb.create_sheet(branch)
    ws.append([f"{branch} branch: October orders"])
    ws.append(["Exported from the shop system"])
    ws.append([])
    ws.append(["order_id", "order_date", "product", "quantity", "unit_price"])
    for line in lines:
        ws.append(list(line))
wb.save("sales.xlsx")
print("wrote customers.csv and sales.xlsx")
PY
uv run make_files.py

The names include accented letters (Aïcha, Hélène, João) on purpose. Customer lists across West and Central Africa mix English, French and Portuguese spellings, and accents are exactly what breaks when the encoding is wrong.

Check it worked

The version line prints 3.1.1 3.1.5 26.0.1 or later patch releases, and the script prints wrote customers.csv and sales.xlsx. ls shows both files next to pyproject.toml. If you open sales.xlsx in a spreadsheet, each sheet has its title in cell A1 and the column names on row 4.

Step 2 · Fix the encoding and the separators

Start with the call most people write first, and see what goes wrong. Write first_look.py:

Bash
cat > first_look.py <<'PY'
import pandas as pd

try:
    pd.read_csv("customers.csv")
except UnicodeDecodeError as err:
    print("UnicodeDecodeError:", err)

df = pd.read_csv("customers.csv", encoding="cp1252")
print(df.shape)
print(df.columns.tolist())
PY
uv run first_look.py

pandas reads files as UTF-8 unless told otherwise. In cp1252 the letter ï is the single byte 0xef, which is not valid UTF-8 on its own, so the first call fails. Passing encoding="cp1252" fixes the text, but the shape is still wrong: pandas split on commas, found no commas in the header and put the whole header in one column. Each data row does contain one comma, the decimal comma in 1.250,50 or 980,00, so every row splits once there into two fields against a one-field header, and pandas uses the first part as the row index. Print df and you will see that odd index on the left.

If you do not know a file's encoding, try utf-8 first, then utf-8-sig (UTF-8 with a byte-order mark, common from Excel's "CSV UTF-8" option), then cp1252. Check a row with accents each time; a wrong single-byte encoding often loads without an error but shows é where é should be.

Now give pandas the separators too. sep=";" splits the fields, decimal="," reads 980,00 as 980.0, and thousands="." drops the dot in 1.250,50:

Bash
cat > read_customers.py <<'PY'
import pandas as pd

df = pd.read_csv("customers.csv", encoding="cp1252", sep=";", decimal=",", thousands=".")
print(df)
print(df.dtypes)
PY
uv run read_customers.py

Check it worked

first_look.py prints a UnicodeDecodeError line mentioning byte 0xef, then (6, 1). read_customers.py prints six rows and six columns with Aïcha Diallo spelt correctly and balance as float64 with values such as 1250.50 and 12400.75. Look at the other types, though: customer_id and phone are int64, so 00042 shows as 42 and 08031234567 as 8031234567, and signup_date is str. The next step fixes those.

Step 3 · Set column types and parse dates at read time

Phone numbers, account numbers, postcodes and IDs look like numbers but are labels: you never add them up, and their leading zeros matter. A Nigerian mobile number written 0803... is not the same string as 803.... Tell pandas to keep these columns as text with dtype, and read the date column with an explicit format so 02/04/2026 means 2 April, not 4 February.

Put the read in a function in read_customers_typed.py, so the later steps can load the file the same way:

Bash
cat > read_customers_typed.py <<'PY'
import pandas as pd


def load_customers():
    return pd.read_csv(
        "customers.csv",
        encoding="cp1252",
        sep=";",
        decimal=",",
        thousands=".",
        dtype={"customer_id": "str", "phone": "str", "city": "category"},
        parse_dates=["signup_date"],
        date_format="%d/%m/%Y",
    )


if __name__ == "__main__":
    customers = load_customers()
    print(customers.head(3))
    print(customers.dtypes)
    print("total balance:", round(customers["balance"].sum(), 2))
    print("signed up in April:", (customers["signup_date"].dt.month == 4).sum())
PY
uv run read_customers_typed.py

A few notes on the choices:

  • str is pandas 3's own text type. In pandas 3 a text column shows as str in dtypes, not the older object.
  • category suits a column with a few repeated values, such as city or branch. It stores each value once and uses less memory.
  • date_format names the exact pattern. Without it pandas has to guess, and day-first dates such as 05/05/2026 are where guesses go wrong. Watch out, though: read_csv does not raise when a value fails to match. It returns the whole column unchanged as text (str in pandas 3), so one bad date such as 31/02/2026 quietly turns signup_date back into strings. Always check that dtypes shows datetime64 for the column. If you want a bad date to fail loudly at load time, read the column as text and convert it afterwards with pd.to_datetime(df["signup_date"], format="%d/%m/%Y"), which raises an error by default.

Check it worked

The first rows show 00042 and 08031234567 with their zeros, and signup_date as 2026-03-17. The types list reads customer_id str, phone str, city category, signup_date datetime64[us] and balance float64. The script prints total balance: 17062.35 and signed up in April: 2 (Aïcha and Kofi).

Step 4 · Read an Excel workbook with several sheets

read_excel reads the first sheet by default and treats row 1 as the header. In sales.xlsx that would make Lagos branch: October orders a column name. header=3 says the header is the fourth row (pandas counts from 0), and sheet_name picks one sheet by name, or every sheet with sheet_name=None.

Bash
cat > read_sales.py <<'PY'
import pandas as pd

sheets = pd.ExcelFile("sales.xlsx").sheet_names
print("sheets:", sheets)

lagos = pd.read_excel("sales.xlsx", sheet_name="Lagos", header=3)
print(lagos)
print(lagos.dtypes)

all_sheets = pd.read_excel("sales.xlsx", sheet_name=None, header=3, dtype={"unit_price": "float64"})
sales = pd.concat(all_sheets, names=["branch", "row"]).reset_index(level="branch").reset_index(drop=True)
print(sales)
print("rows:", len(sales))
PY
uv run read_sales.py

With sheet_name=None you get a dictionary of sheet name to DataFrame. pd.concat stacks them and uses the dictionary keys as an extra index level, which reset_index(level="branch") turns into a normal branch column. Now you can tell which branch each order came from without adding a column by hand in the spreadsheet.

Look at unit_price in the Lagos sheet on its own: it comes back as int64, because every Lagos price happens to be a whole number. Accra has 8.5. The dtype={"unit_price": "float64"} on the combined read means the column has one type whatever each sheet holds. Dates stored as real Excel dates come back as datetime64 without any format; dates typed as text in a sheet would need the same date_format treatment as the CSV.

Check it worked

The script lists ['Lagos', 'Nairobi', 'Accra'], prints the three Lagos orders with order_id as the first column name (not the title text), shows order_date datetime64[us], and ends with a seven-row table whose first column is branch and the line rows: 7.

Step 5 · Write Parquet and compare it with CSV

A CSV holds text and nothing else. Every time you read it, pandas guesses the types again, and all the work from the previous steps is lost. Parquet stores each column with its type, compressed, so what you write is what you get back.

to_parquet.py saves the typed customers table both ways and reads each back, then builds a larger table of 200,000 generated orders to show the size difference:

Bash
cat > to_parquet.py <<'PY'
from pathlib import Path

import numpy as np
import pandas as pd

from read_customers_typed import load_customers

customers = load_customers()
customers.to_csv("customers_clean.csv", index=False)
customers.to_parquet("customers.parquet", index=False)

print("from CSV:")
print(pd.read_csv("customers_clean.csv").dtypes)
print("from Parquet:")
back = pd.read_parquet("customers.parquet")
print(back.dtypes)
print("first ID from Parquet:", back["customer_id"].iloc[0])

# A bigger table shows the size difference: 200,000 orders.
rng = np.random.default_rng(7)
n = 200_000
orders = pd.DataFrame({
    "order_id": [f"ORD-{i:07d}" for i in range(n)],
    "branch": pd.Categorical(rng.choice(["Lagos", "Nairobi", "Accra", "Dakar"], n)),
    "order_date": pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 300, n), unit="D"),
    "quantity": rng.integers(1, 20, n),
    "unit_price": rng.uniform(1, 500, n).round(2),
})
orders.to_csv("orders.csv", index=False)
orders.to_parquet("orders.parquet", index=False)
for name in ("orders.csv", "orders.parquet"):
    print(name, round(Path(name).stat().st_size / 1_000_000, 1), "MB")
PY
uv run to_parquet.py

The CSV round trip undoes everything: customer_id and phone are numbers again and the date is text. The Parquet round trip keeps str, category and datetime64, and the first ID is still 00042. Parquet also needs no encoding, sep or decimal arguments, so there is nothing for the next person to get wrong.

Keep CSV for handing data to people who open it in a spreadsheet. Use Parquet for files your own scripts read again, such as the output of a cleaning step. If you share data over a prepaid mobile connection, the smaller file also costs less to send.

Check it worked

Under from CSV: you see customer_id int64 and signup_date str; under from Parquet: you see customer_id str and signup_date datetime64[us], then first ID from Parquet: 00042. The last two lines give sizes of something like orders.csv 7.7 MB and orders.parquet 2.2 MB: the Parquet file is roughly a third of the size.

Step 6 · Read only the columns you need

A file with 40 columns where you need three is common, and loading all 40 wastes memory. That matters on a laptop with 4 GB or 8 GB of RAM, which is what many analysts work on. Peek at the first rows with nrows, then load only the columns you use:

Bash
cat > needed_columns.py <<'PY'
import pandas as pd

peek = pd.read_csv("orders.csv", nrows=5)
print(peek)

wanted = ["branch", "quantity", "unit_price"]
everything = pd.read_parquet("orders.parquet")
from_parquet = pd.read_parquet("orders.parquet", columns=wanted)
from_csv = pd.read_csv("orders.csv", usecols=wanted, dtype={"branch": "category"})

for label, frame in (("all columns", everything), ("Parquet, 3 columns", from_parquet), ("CSV, 3 columns", from_csv)):
    mb = frame.memory_usage(deep=True).sum() / 1_000_000
    print(f"{label}: {frame.shape}, {mb:.1f} MB in memory")

lagos = pd.read_parquet("orders.parquet", columns=wanted, filters=[("branch", "==", "Lagos")])
print("Lagos rows:", len(lagos))
print("Lagos revenue:", round((lagos["quantity"] * lagos["unit_price"]).sum(), 2))
PY
uv run needed_columns.py

usecols in read_csv still scans the whole file but keeps only the named columns. Parquet goes further: it stores each column separately, so columns= reads only those parts of the file from disk. filters= skips rows as well; here it loads only Lagos orders. read_excel takes usecols too, either a list of names or a spreadsheet range such as "A:D".

Check it worked

The peek shows five rows and all five columns. The memory lines read something like all columns: (200000, 5), 8.8 MB and Parquet, 3 columns: (200000, 3), 3.4 MB, with the CSV three-column read about the same as the Parquet one. Then you see Lagos rows: with a number close to 50,000 (a quarter of the orders) and a revenue figure. Your exact numbers can differ slightly with other NumPy versions.

When you have finished, remove the demo folder:

Bash
cd ~
rm -rf ~/read-files-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.