Data Sources & File Formats

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Before any analysis there is a data file, a database or an API, and most of the surprises in a project start there: a date that is read as text, a leading zero that disappears from a postal code, a file that fits on disk but not in memory, an Excel sheet with a title above the header row. This page covers where data comes from, which file formats are worth knowing and when to choose each, and how to read and write them safely with the Python standard library, pandas and PyArrow. Examples target Python 3.13 or 3.14 and were run on Python 3.13. The page targets pandas 3.1 (with PyArrow 26 installed) and scikit-learn 1.9, and everything was checked in October 2026. Every example in this page that works with local files was executed with those versions inside a scratch directory.

The examples share one tiny file, people.csv, which the first example creates. It has a quoted field containing a comma, a missing value and ISO dates, which are exactly the features that make real files awkward:

import csv
from pathlib import Path

Path("people.csv").write_text(
    "id,name,city,signup,score\n"
    "1,Ana,Madrid,2026-01-05,8.5\n"
    "2,Luis,\"Bilbao, ES\",2026-02-11,\n"
    "3,Marta,Sevilla,2026-03-20,7.25\n",
    encoding="utf-8",
)

with open("people.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row)

Source: csv (Python documentation). Output:

{'id': '1', 'name': 'Ana', 'city': 'Madrid', 'signup': '2026-01-05', 'score': '8.5'}
{'id': '2', 'name': 'Luis', 'city': 'Bilbao, ES', 'signup': '2026-02-11', 'score': ''}
{'id': '3', 'name': 'Marta', 'city': 'Sevilla', 'signup': '2026-03-20', 'score': '7.25'}

Notice that the csv module returns text for every field, including the number and the date, and an empty string for the missing score. It does no type conversion. It also handled the quoted comma correctly, which line.split(",") would not. Always open CSV files with newline="" and an explicit encoding, as the documentation requires.

Where data comes from

Source What to know Typical tools

Files you were given (CSV, Excel, JSON, Parquet)

The most common case. Ask for a data dictionary: column meanings, units, how missing values are coded, the time zone of timestamps and how the file was produced.

pandas.read_*, csv, json, PyArrow

Relational databases

Data is already typed and constrained; the query does the first filtering and aggregation, close to the data. See SQL aggregate and window functions and Choosing the Right Database.

SQLAlchemy and pandas.read_sql, or a database driver

Web APIs and web pages

Respect terms of use, rate limits and authentication; cache responses so that repeated runs do not hit the service. Prefer an official API or download to scraping.

urllib, requests or httpx, then json_normalize

Public datasets and open data portals

Check the licence and the date of the snapshot; portals often change file layouts without notice.

The repositories listed below

Datasets bundled with libraries

Small, versioned and offline, ideal for learning and tests; not representative of real work.

sklearn.datasets, seaborn.load_dataset

Public repositories

  • UCI Machine Learning Repository (archive.ics.uci.edu) is a long-standing collection of datasets with descriptions and, for many of them, a documented target variable.

  • OpenML (openml.org) hosts datasets with metadata and benchmark tasks; scikit-learn can download them with fetch_openml.

  • data.europa.eu is the portal of the European Union’s open data, and data.gov is the United States government’s catalogue. Both aggregate datasets published by agencies, with licence information and often several formats.

  • Hugging Face Datasets (huggingface.co/datasets) hosts datasets, mostly text, image and audio, loaded with the datasets library. For the model side see the Hugging Face Hub essentials.

Loading datasets from scikit-learn and OpenML:

from sklearn.datasets import fetch_openml, load_iris

iris = load_iris(as_frame=True)
print(type(iris.frame), iris.frame.shape)     # a pandas DataFrame with 150 rows and 5 columns

# downloaded once, then cached in ~/scikit_learn_data (needs internet the first time)
adult = fetch_openml("adult", version=2, as_frame=True)
X, y = adult.data, adult.target

Source: Dataset loading utilities (scikit-learn). The first two lines were executed on the pinned versions and print <class 'pandas.DataFrame'> (150, 5). The fetch_openml call needs network access and was not executed here. Older tutorials use fetch_mldata (the service it used, mldata.org, no longer exists) or load_boston (removed in scikit-learn 1.2 because of ethical problems with the data): replace them with fetch_california_housing or fetch_openml. fetch_openml now returns a DataFrame by default (as_frame="auto"), so code that indexes the result with X[0] fails: use X.iloc[0].

Loading from Hugging Face Datasets:

from datasets import load_dataset

ds = load_dataset("imdb", split="train")     # downloads and caches the dataset
df = ds.to_pandas()

Source: Hugging Face Datasets documentation. This example needs the datasets package and network access and was not executed here.

Whatever the source, record where each file came from, when, under which licence, and a checksum. A data/README file with that information, committed beside the code, answers "which version of the data produced this result?" months later. Personal data adds legal duties: see Ethics, Privacy & Responsible Data Use.

Choosing a format

flowchart TD A["Need to store or exchange a table"] --> B{"Will people open it in a spreadsheet?"} B -- Yes --> C["CSV for plain data XLSX for formatting and several sheets"] B -- No --> D{"Nested or irregular records, for example from an API?"} D -- Yes --> E["JSON, or JSON Lines for large, appendable files"] D -- No --> F{"Large table, repeated analytical queries?"} F -- Yes --> G["Parquet: columnar, typed, compressed"] F -- No --> H{"Concurrent writers, updates, or relationships between tables?"} H -- Yes --> I["A database: SQLite for one machine, PostgreSQL and similar for servers"] H -- No --> J["Parquet again, or Feather for fast temporary files"]
Format Strengths Weaknesses Use it for

CSV

Universal, human-readable, streams well, every tool reads it.

No types, no schema; dates, booleans and missing values are conventions; encoding and delimiter vary; large files are slow and big.

Exchange with people and legacy systems; small inputs.

JSON and JSON Lines

Nested structures; JSON Lines (one record per line) is appendable and streamable.

Verbose; nesting must be flattened; ambiguous numeric types.

API responses, logs, configuration, semi-structured records.

Excel (.xlsx)

What business users have; several sheets; formatting.

Merged cells, titles above headers and hidden rows; dates stored as numbers; silent type coercion by the application; row limit; slow.

Receiving reports. Do not use it as a storage format for analysis.

Parquet

Columnar, typed, compressed, supports column selection and filters without reading the entire file, the de facto format for analytics.

Not human-readable; not designed for frequent row-level updates.

The default for datasets you produce and reuse.

Arrow IPC and Feather

The in-memory Arrow layout on disk: very fast to read and to share between processes and languages.

Less compact than Parquet; designed for short-term exchange more than archival.

Handing data between tools, caches.

SQLite and other databases

Typed, indexed, transactional, queried with SQL.

Needs a schema; a server for most engines.

Data that changes, is shared, or is queried in many different ways.

pickle, joblib

Store any Python object.

Tied to Python and library versions, and unsafe to load from untrusted sources because loading can execute code.

Short-lived caches only; never as a data exchange format.

CSV with pandas

pandas.read_csv is the workhorse. It guesses types, so the guess must be controlled whenever the data matters:

import pandas as pd

df = pd.read_csv(
    "people.csv",
    dtype={"id": "int32", "city": "category"},
    parse_dates=["signup"],
    na_values=["", "NA"],
)
print(df)
print(df.dtypes)

Source: pandas.read_csv. Output on pandas 3.1:

   id   name        city     signup  score
0   1    Ana      Madrid 2026-01-05   8.50
1   2   Luis  Bilbao, ES 2026-02-11    NaN
2   3  Marta     Sevilla 2026-03-20   7.25
id                 int32
name                 str
city            category
signup    datetime64[us]
score            float64
dtype: object

Two details are specific to pandas 3. Text columns now have the dedicated str dtype by default instead of object (with NaN as the missing value), so code that tests ser.dtype == object returns False; use pd.api.types.is_string_dtype instead. And datetimes default to microsecond resolution (datetime64[us]), so converting to integers gives values one thousand times smaller than code written for nanoseconds expects. See Data Cleaning & Preparation for the full treatment of types and missing values.

The options that matter

Option Why and when

dtype=

Declare types explicitly. Keep identifiers with leading zeros (postal codes, product codes) as strings, or they become integers and the zeros are lost. category saves memory for low-cardinality text.

parse_dates=

Parse listed columns as dates. Dates in other layouts need an explicit format, and day-first dates are a classic trap: 03/04/2026 is 3 April in most of the world and 4 March in the United States. Pass the format; do not rely on guessing.

na_values= and keep_default_na=

Which strings mean "missing". Defaults include empty text, NA and NaN. Data that uses -999, ? or N/A as a sentinel must say so, or those values stay as ordinary data and silently distort means.

usecols= and nrows=

Read only some columns or the first rows: the quickest way to inspect a file that is too large to open.

sep=, decimal=, thousands=

European exports often use ; as the separator and , as the decimal mark.

encoding=

utf-8 is the default. Files from Windows tools are frequently cp1252 or latin-1; a file with a byte order mark needs utf-8-sig. A UnicodeDecodeError or text such as María means the encoding is wrong.

header=, skiprows=, names=

Files with title lines above the header, or none at all.

chunksize= and iterator=

Process a file in pieces; see below.

dtype_backend="pyarrow"

Use Arrow-backed types, which keep integers when values are missing and make strings and dates cheaper.

engine="pyarrow"

A multi-threaded parser that is often much faster on large files, with some options unsupported.

Selecting columns and reading in chunks

import pandas as pd

# only the needed columns, and only the first rows
small = pd.read_csv("people.csv", usecols=["id", "score"], nrows=2)
print(small)

# chunked reading for files larger than memory
total = 0.0
for chunk in pd.read_csv("people.csv", chunksize=2):
    total += chunk["score"].sum()
print(total)    # 15.75

Source: IO tools: iterating through files chunk by chunk. Chunks suit aggregations that can be combined (sums, counts, filters). Operations that need all rows at once, such as a global median or a sort, do not. For those, convert the CSV to Parquet once and use columnar tools, or use a database or an engine such as DuckDB (see Beyond the Core: Polars, Arrow, DuckDB & Deep Learning).

Writing CSV: df.to_csv("out.csv", index=False). Always pass index=False unless the index carries information, or the next reader finds an unnamed extra column. CSV loses types, so a round trip through CSV is not the identity: categories, time zones and integer-with-missing columns come back changed.

JSON and JSON Lines

JSON files from APIs are usually nested. The standard library parses them and pandas.json_normalize flattens records:

import json
import pandas as pd
from pathlib import Path

records = [
    {"id": 1, "user": {"name": "Ana", "tags": ["a", "b"]}},
    {"id": 2, "user": {"name": "Luis", "tags": []}},
]
Path("data.json").write_text(json.dumps(records), encoding="utf-8")
print(pd.json_normalize(records, sep="_"))

pd.DataFrame(records).to_json("data.jsonl", orient="records", lines=True)
print(pd.read_json("data.jsonl", lines=True))

Source: pandas.json_normalize and pandas.read_json. The first table shows user_name and user_tags as flattened columns (lists stay as list objects: use explode to turn them into rows). lines=True reads and writes JSON Lines, which is preferable to one giant array for large or growing data because a reader can process it record by record and a writer can append to it.

Excel

import pandas as pd

df = pd.read_csv("people.csv")
df.to_excel("people.xlsx", sheet_name="people", index=False)
print(pd.read_excel("people.xlsx", sheet_name="people"))

Source: pandas.read_excel. Reading and writing .xlsx needs the optional openpyxl package; .xls needs xlrd. Under pandas 3.1, read_excel on an .xlsx file without an explicit engine emits a Pandas4Warning: the default reader for .xlsx and .xlsm will change from openpyxl to calamine (the python-calamine package, which also reads .xls, .xlsb and .ods) in a future version. Pass engine="openpyxl" to keep the current reader, or engine="calamine" to adopt the new one, and the warning goes away. The options sheet_name (name, index, a list, or None for all sheets as a dictionary), header, skiprows, usecols and dtype mirror read_csv. Spreadsheets in the wild contain merged cells, notes above the table, totals row at the bottom and hidden sheets: inspect them in the application first and use skiprows and nrows to select the data rectangle. Dates stored as numbers and text-formatted numbers are typical sources of silent errors. Never open a CSV in Excel and save it back if the file matters: it re-types columns (leading zeros, long identifiers, gene names that look like dates).

Parquet and Arrow

Apache Parquet stores a table by column in compressed chunks called row groups, with the schema and statistics in the file. Apache Arrow is the matching in-memory columnar format that pandas 3 uses for its string dtype when PyArrow is installed, and PyArrow reads and writes Parquet.

import pandas as pd
import pyarrow.parquet as pq

df = pd.read_csv("people.csv", parse_dates=["signup"])
df.to_parquet("people.parquet", compression="zstd", index=False)

# read only some columns
print(pd.read_parquet("people.parquet", columns=["id", "score"]))

# inspect the schema and layout without loading the data
pf = pq.ParquetFile("people.parquet")
print(pf.schema_arrow)
print(pf.metadata.num_rows, pf.metadata.num_row_groups)

# a filter applied while reading, so less data reaches pandas
print(pd.read_parquet("people.parquet", filters=[("score", ">", 8)]))
   id  score
0   1   8.50
1   2    NaN
2   3   7.25
id: int64
name: large_string
city: large_string
signup: timestamp[us]
score: double
-- schema metadata --
pandas: '{"index_columns": [], "column_indexes": [], "columns": [{"name":' + 634
3 1
   id name    city     signup  score
0   1  Ana  Madrid 2026-01-05    8.5

Parquet keeps types (dates stay dates, integers stay integers) and is usually several times smaller than the equivalent CSV and much faster to read, especially when you need a few columns. Practical advice:

  • Convert a CSV you will read more than a couple of times into Parquet once. Keep the CSV as the raw, untouched source.

  • Use compression="zstd" or the default snappy; zstd is smaller at similar speed.

  • Large datasets are best stored as a directory of files partitioned by a column (df.to_parquet("out", partition_cols=["year"])), so queries on year skip other files. Do not create thousands of tiny files: aim for files of tens to hundreds of megabytes.

  • Parquet is written once and read many times. For frequently updated data, use a database.

  • The Feather format (df.to_feather) is the Arrow IPC file: fastest to read, good for temporary handoffs between Python and R, not meant for long-term archives.

Related tools read the same files without pandas: Polars, DuckDB (SELECT * FROM 'people.parquet') and Spark. This is why Parquet is the common interchange between them, covered in Beyond the Core: Polars, Arrow, DuckDB & Deep Learning.

SQL databases

pandas reads query results into a DataFrame and writes a DataFrame to a table through a SQLAlchemy connectable:

import pandas as pd
from sqlalchemy import create_engine, text

df = pd.read_csv("people.csv")
engine = create_engine("sqlite:///people.db")
df.to_sql("people", engine, if_exists="replace", index=False)

with engine.connect() as conn:
    out = pd.read_sql(
        text("SELECT city, AVG(score) AS avg_score FROM people WHERE id >= :min_id GROUP BY city"),
        conn,
        params={"min_id": 1},
    )
print(out)
         city  avg_score
0  Bilbao, ES        NaN
1      Madrid       8.50
2     Sevilla       7.25

Three rules apply. First, always pass values as bound parameters (:min_id with params=), never by formatting them into the query string, which invites SQL injection and quoting errors. Second, push the filtering and aggregation into the query: transferring a few thousand aggregated rows is cheaper than transferring millions and aggregating in pandas. Third, to_sql is convenient for analysis databases but does not manage schemas, indexes or migrations; for application databases use the tools described in the database section of this site. The same functions work with PostgreSQL, MySQL and other engines by changing the connection URL; keep credentials in environment variables, not in the notebook. R users have the equivalent in Databases with DBI.

Reading over HTTP

pd.read_csv and pd.read_parquet accept URLs directly, and the standard library fetches bytes for anything else:

import io
import urllib.request
import pandas as pd

url = "https://example.com/data.csv"      # replace with a real address
with urllib.request.urlopen(url, timeout=30) as resp:
    df = pd.read_csv(io.BytesIO(resp.read()))
print(df.shape)

Source: urllib.request (Python documentation). The example was run against a local file:// address of people.csv and printed (3, 5). For notebooks, download once into a data/raw folder and read the local copy afterwards: it is faster, works offline and keeps the analysis reproducible even if the source changes or disappears. Always set a timeout, check the status of the response, and never download and execute code or unpickle files from sources you do not trust.

A reading checklist

Run these checks on every new dataset, immediately after loading:

print(df.shape)
print(df.dtypes)
print(df.isna().sum())
print(df.describe(include="all"))
print(df.duplicated().sum(), "duplicate rows")
print(df.head(), df.tail(), sep="\n")

Source: Essential basic functionality (pandas). Compare row counts with the source’s documentation, check the minimum and maximum of dates and numbers, make sure identifiers are unique when they should be, and look at the last rows as well as the first, since footers and truncated writes appear there. The next steps are Data Cleaning & Preparation and Exploratory Data Analysis. For R users reading text files the equivalent page is Reading and Writing Text Data.

Where older books and tutorials are outdated

Older statement Current practice (October 2026)

fetch_mldata loads MNIST and other datasets (scikit-learn before 0.20).

The service no longer exists; use fetch_openml. Its default return type is now a DataFrame, so X[0] fails.

load_boston is the standard regression example.

Removed in scikit-learn 1.2. Use fetch_california_housing or fetch_openml.

from sklearn.externals import joblib

Removed; import joblib directly.

DataFrame.append accumulates rows read in a loop.

Removed in pandas 2.0. Collect frames in a list and call pd.concat once.

pd.read_csv(...) text columns have dtype object.

In pandas 3 they are str by default; test with pd.api.types.is_string_dtype.

pd.read_msgpack, pd.read_gbq, .ix for reading and selecting.

Removed (msgpack in 1.0, read_gbq in 3.0). Use Parquet, or the Google BigQuery client libraries.

Data is read with Python 2 idioms (open(file, "rb") for CSV, print statements).

Open text CSV files with newline="" and an explicit encoding, and use Python 3.