# Extract tables from PDFs in Python

Get the tables of a PDF as rows and cells in Python, with numbers as typed values and a pandas DataFrame per table. Scanned PDFs work too.

This guide reads the tables of a PDF into Python. The PDF goes to the [PDF table extraction API](https://switchfile.io/pdf-table-extraction-api) with the target `json`, and the answer is the [Document JSON](https://switchfile.io/docs/document-json): each page with its blocks in reading order, and each table that was found with two or more columns as a table block with its cells. Tables without lines are found too, and `source` tells you which kind a table is. A table with a single column comes back as one paragraph per row, not as a table block, so the code below does not turn it into rows.

## 1. Install the SDK and set the key

The SDK needs Python 3.10 or later. pandas is only needed for step 5.

```bash
pip install switchfile-sdk pandas
export SWITCHFILE_API_KEY="sf_live_..."
```

Create the key in the dashboard under [API keys](https://switchfile.io/dashboard/keys). A script can also [get a key without a browser](https://switchfile.io/docs/authentication#get-an-api-key-without-a-browser). A free account converts 20 files and 20 minutes of conversion time a day, whichever runs out first, each PDF with up to 50 pages.

## 2. Convert the PDF to JSON

pdf_tables.py:

```python
import json
import os

import switchfile

switchfile.configure(api_key=os.environ["SWITCHFILE_API_KEY"])
conversion = switchfile.convert("report.pdf", "json")
result = conversion["result"]
if result["incomplete"]:
    raise SystemExit("\n".join(["The result is incomplete:", *result.get("notes", [])]))
document = json.loads(switchfile.download(conversion))
```

When pages could not be read, `result["incomplete"]` is `True` and `result["notes"]` names them. The script then stops, so no table goes on without its missing pages. `download` without a file name returns the bytes of the result. Scanned pages are read with text recognition. To set their language, pass it as an option, for example `{"ocr_language": "deu"}` for German.

## 3. Turn each table into rows

A table has `rows` and `cols`. Each cell has its `row` and `col`, counted from 0, and its `text`. Empty cells are left out, so start with an empty grid and fill in the cells:

```python
def table_rows(table):
    rows = [[""] * table["cols"] for _ in range(table["rows"])]
    for cell in table["cells"]:
        rows[cell["row"]][cell["col"]] = cell["text"]
    return rows


for page in document["pages"]:
    for block in page.get("blocks", []):
        if block["type"] == "table":
            rows = table_rows(block)
            print(f"page {page['number']}: {len(rows)} rows, {block['cols']} columns")
```

A merged cell carries `rowspan` or `colspan` and stands once, at its `row` and `col`. A table that runs over several pages stands once, on its first page, so you do not need to join its parts.

## 4. Numbers as values

A cell that reads as a number has a `value` next to its `text`, for example `1234.5` for `1,234.50`. A percentage comes as a fraction, and a date as `YYYY-MM-DD`:

```python
def cell_value(cell):
    value = cell.get("value")
    return value["value"] if value else cell["text"]
```

A number like `1.234` can be read in two ways. It is read the way the other numbers of the table are written, so compare `value` with `text` where such a column matters to you. Every type is listed under [Typed values](https://switchfile.io/docs/document-json#values).

## 5. A pandas DataFrame per table

```python
import pandas as pd


def table_frame(table):
    rows = [[None] * table["cols"] for _ in range(table["rows"])]
    for cell in table["cells"]:
        rows[cell["row"]][cell["col"]] = cell_value(cell)
    if table.get("header_rows") == 1:
        return pd.DataFrame(rows[1:], columns=rows[0])
    return pd.DataFrame(rows)


frames = [table_frame(b) for p in document["pages"] for b in p.get("blocks", []) if b["type"] == "table"]
for i, frame in enumerate(frames, start=1):
    frame.to_csv(f"table-{i}.csv", index=False)
```

`header_rows` is the number of header rows where it is known. With one header row, its cells become the column names.

## Which cells come from a scan

A page whose text comes from text recognition has `"ocr": true`. Check the values of such tables before you use them for anything that counts. There are no confidence scores.

```python
scanned = [p["number"] for p in document["pages"] if p.get("ocr")]
```

## What it costs

PDF to JSON uses 1 credit per started minute of conversion time, at least 1 per file. The free daily quota comes first, and PDFs have the same [page limits](https://switchfile.io/docs/limits#pdf-office-pages) as PDF to Word. `switchfile.estimate("report.pdf", "json")` returns the credits and the price of a file before you convert it.

Our open test of PDF tables is public, with its documents and the scoring code: [pdf-table-bench](https://github.com/switchfile/pdf-table-bench).

## Next

- [Document JSON](https://switchfile.io/docs/document-json): Convert a PDF or an Office file to json and get its pages as data, with text blocks in reading order and tables as cells.
- [Simple API](https://switchfile.io/docs/simple-api): Convert a file with one request to the switchfile simple API (v1). Synchronous and asynchronous requests, the conversion object, batches, ZIP files and cost estimates.
