Data Types for Data Science in Python

Datatypes Mar 19, 2026

Data Types for Data Science in Python – Complete Guide 2026

Understanding Python data types and how they map to pandas/NumPy types is fundamental for efficient data science workflows. Choosing the right data type can reduce memory usage by 50-90% and significantly improve performance when working with large datasets.

TL;DR — Most Important Data Types in Data Science 2026

  • Numeric: int64, float64, float32, Int64 (nullable)
  • Text: object, string (pandas StringDtype)
  • Boolean: bool, boolean (nullable)
  • Date/Time: datetime64[ns], datetime64[ns, tz]
  • Categorical: category – huge memory saver for repeated values

1. Core Numeric Types

import pandas as pd
import numpy as np

# Small inline sample so this example runs as-is.
# In a real project you would load it: df = pd.read_csv("sales_data.csv")
df = pd.DataFrame({
    "customer_id": [101, 102, 103, 104, 105, 106],
    "customer_name": ["Ana", "Ben", "Chen", "Dana", "Eli", "Fay"],
    "order_date": ["2026-01-05", "2026-01-12", "2026-02-03",
                   "2026-02-18", "2026-03-01", "2026-03-09"],
    "amount": [1250.75, 890.50, 2340.00, 1780.25, 2615.40, 450.00],
    "quantity": [3, 2, 5, 4, 6, 1],
    "profit": [312.69, 222.63, 585.00, 445.06, 653.85, 112.50],
    "region": ["North", "South", "East", "North", "West", "South"],
    "category": ["Electronics", "Books", "Electronics", "Home", "Home", "Books"],
    "rating": [5, 4, None, 3, 5, 4],
})

# Default types (often wasteful)
print(df.dtypes)

# Optimized types - huge memory savings
df = df.astype({
    "customer_id": "int32",
    "amount": "float32",
    "quantity": "int16",
    "profit": "float32"
})

print("Memory usage after optimization:")
print(df.memory_usage(deep=True).sum() / (1024**2), "MB")

2. String vs Object vs pandas StringDtype

# Old way - object (slow and memory heavy)
df["customer_name"] = df["customer_name"].astype("object")

# Modern recommended way in 2026
df["customer_name"] = df["customer_name"].astype("string")   # pandas StringDtype

# Even better for categorical text
df["region"] = df["region"].astype("category")

3. Boolean and Nullable Types

# Nullable integer and boolean (handles missing values gracefully)
df["is_high_value"] = df["amount"] > 1500
df["is_high_value"] = df["is_high_value"].astype("boolean")   # nullable boolean

# Nullable integer
df["rating"] = df["rating"].astype("Int64")   # capital I for nullable

4. Date and Time Types

df["order_date"] = pd.to_datetime(df["order_date"], format="%Y-%m-%d")

# With timezone awareness (recommended)
df["order_date"] = pd.to_datetime(df["order_date"]).dt.tz_localize("UTC")

# Extract useful components
df["year"] = df["order_date"].dt.year
df["month"] = df["order_date"].dt.month
df["day_of_week"] = df["order_date"].dt.day_name()

5. Best Practices for Data Types in 2026

  • Always specify dtypes when reading CSV to avoid default object/float64
  • Use category for columns with few unique values (region, category, status)
  • Use float32 instead of float64 when precision is not critical
  • Prefer nullable types (Int64, boolean, string) for real-world messy data
  • Run df.info(memory_usage="deep") regularly to monitor memory

Why Data Types Change Results, Not Just Memory

A data type decides which operations are allowed and how values behave. If a numeric column is read as text, sum() concatenates strings or fails, sorting becomes alphabetical ("100" before "9"), and comparisons like amount > 1500 raise errors. Getting types right early prevents silent bugs later in the pipeline.

Note that pandas 3.0 stores text columns with the dedicated str dtype by default instead of the generic object dtype. Code that checks dtype == "object" to find text columns should use pd.api.types.is_string_dtype() instead.

Worked Example: Cleaning a Messy Column

Raw exports often contain numbers stored as text, with thousands separators and placeholders for missing values. Here is a safe way to convert them:

import pandas as pd

raw = pd.DataFrame({"amount": ["1,250.75", "890.50", "n/a", "2,340"]})

clean = (
    raw["amount"]
    .str.replace(",", "", regex=False)          # drop thousands separators
    .pipe(pd.to_numeric, errors="coerce")        # "n/a" becomes NaN
    .astype("Float64")                           # nullable float
)
raw["amount"] = clean

print(raw.dtypes)
print(raw["amount"].sum())                       # missing values are skipped
print(raw["amount"].isna().sum(), "missing value(s)")

errors="coerce" turns anything unparseable into a missing value instead of crashing, so you can count and inspect the problem rows rather than losing the whole load.

Common Mistakes

  • Downcasting without checking the range: int16 only holds values from -32,768 to 32,767; check df[col].max() first
  • Using float32 for money when exact cents matter; keep float64 or store integer cents
  • Converting high-cardinality text to category: it helps only when values repeat a lot
  • Calling astype("int64") on a column with missing values: it raises an error; use "Int64" instead

Quick Summary

  • Inspect types with df.dtypes and df.info(memory_usage="deep") right after loading
  • Use nullable types (Int64, boolean, Float64) when data has gaps
  • Convert text numbers with pd.to_numeric(errors="coerce") and dates with pd.to_datetime

Conclusion

Choosing the right data types is one of the easiest and most effective ways to optimize memory and speed in data science projects. In 2026, the combination of proper dtype specification, pandas nullable types, category dtype, and string dtype can reduce memory usage dramatically while making your code more robust to missing values.

Next steps:

  • Check your current datasets with df.info(memory_usage="deep") and optimize the data types using the patterns above

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices