HOWTO · Python

How to Read CSV to Array in Python

This tutorial demonstrates how to read a CSV into an array in Python.

On this page

CSV files store tabular records as rows of delimited fields. To read one in Python, choose a reader based on the data and the structure you need: NumPy for numeric arrays, Python’s standard-library csv module for rows of strings, or pandas for labeled tables. All four examples have passing runtime evidence, and each creates its own temporary CSV file.

Read numeric CSV data with numpy.loadtxt()

Use numpy.loadtxt() when the fields are consistently numeric and arranged in a regular table. Its delimiter argument describes the separator in the input text. It does not appear in the returned array; commas are parsed between values. The default delimiter is whitespace, so set it to a comma for comma-separated data. NumPy must be installed to run this example.

Run this example:

from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np

with TemporaryDirectory() as directory:
    path = Path(directory) / "numbers.csv"
    path.write_text("1,2,3\n4,5,6\n7,8,9\n", encoding="utf-8")
    data_array = np.loadtxt(path, delimiter=",")
    print(data_array)

loadtxt() returns a two-dimensional NumPy array for this multirow, multicolumn input. Use its array operations for numerical work. If the file has a header, skip or handle that row explicitly rather than asking the numeric reader to parse it as numbers.

Read CSV rows with Python’s csv module

The standard-library csv.reader works with fields that are text or have different kinds of values. It yields one list of strings per row. Calling the built-in list() consumes the reader and materializes all those rows as a list of lists; list() is a built-in function, not a method, and its result is not a NumPy array. This is useful when you want to inspect or transform each field yourself.

from pathlib import Path
from tempfile import TemporaryDirectory
import csv

with TemporaryDirectory() as directory:
    path = Path(directory) / "people.csv"
    path.write_text(
        "Name,Age,Occupation\nJohn,28,Engineer\nJane,34,Doctor\n",
        encoding="utf-8",
    )
    with path.open(newline="", encoding="utf-8") as file:
        rows = list(csv.reader(file))
    print(rows)

The header is included as the first row, and values such as ages remain strings until you convert them. For large files, iterate over csv.reader one row at a time instead of building a list containing the entire file. Opening with newline="" lets the CSV module handle line endings correctly.

Read CSV data with pandas

Choose pandas when column labels and table-oriented operations are useful. Install pandas before running this example. pandas.read_csv() uses the first row as column names by default and returns a labeled DataFrame. Convert its data to an array with to_numpy() when a downstream operation needs an array; the DataFrame itself retains column and row labels.

from pathlib import Path
from tempfile import TemporaryDirectory
import pandas as pd

with TemporaryDirectory() as directory:
    path = Path(directory) / "people.csv"
    path.write_text(
        "Name,Age,Occupation\nJohn,28,Engineer\nJane,34,Doctor\n",
        encoding="utf-8",
    )
    frame = pd.read_csv(path)
    data_array = frame.to_numpy()
    print(data_array)

Pandas may infer different types for different columns in the DataFrame. A single NumPy array must have one dtype, so converting mixed columns can produce an object array or another common dtype. Keep the DataFrame if labels and per-column operations matter; convert only when an array is the interface your next step requires.

Handle missing numeric values with numpy.genfromtxt()

For numeric tables with blank fields, use numpy.genfromtxt() and choose a fill value that fits the next calculation. Here filling_values=np.nan marks a missing numeric value as NaN; the result uses floating-point values so it can represent that marker. NumPy must be installed.

from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np

with TemporaryDirectory() as directory:
    path = Path(directory) / "measurements.csv"
    path.write_text("1,2,3\n4,,6\n7,8,\n", encoding="utf-8")
    data_array = np.genfromtxt(
        path, delimiter=",", filling_values=np.nan
    )
    print(data_array)

The blank fields are represented by NaN, which can be detected with NumPy’s isnan functions and handled before calculations that require ordinary numbers. genfromtxt() also supports more involved input cleanup, but specify only the options your file needs so the parsing behavior stays clear.

Choose a CSV reader for your data

  • Use numpy.loadtxt() for regular numeric fields when a NumPy array is the desired result.
  • Use csv.reader when you want rows of strings and control over how each field is converted. It is included with Python.
  • Use pandas.read_csv() for labeled tables and convenient column-based processing; convert to an array only when needed.
  • Use numpy.genfromtxt() for numeric delimited data with missing fields when a chosen fill value is appropriate.

These tools do not all return the same kind of object. Decide whether you need labels, string fields, numeric array operations, or explicit handling for missing numbers, then select the reader that produces that structure.