How to convert a NumPy array dtype

NumPy dtypes decide how array values are stored, compared, and handed to later calculations. Converting an array dtype is useful when imported text should become numeric data, floating-point results need whole-number storage, or a saved array needs a predictable binary representation.

The astype() method creates an array with the requested dtype while keeping the original shape. Its default casting rule is permissive for compatibility, so a float-to-integer conversion can truncate fractional values and still finish without an error.

Use explicit dtype names such as np.float64 and np.int64 when the storage type matters outside the current line of code. Printing both dtype and values after conversion catches cases where the dtype changed successfully but the numeric meaning changed too.

Steps to convert a NumPy array dtype:

  1. Create a script that converts string values, default integer casts, and strict whole-number casts.
    array-convert-dtype.py
    import numpy as np
     
    raw = np.array(["1.25", "2.50", "3.75"])
    floats = raw.astype(np.float64)
    truncated = floats.astype(np.int64)
    whole = np.array([10.0, 20.0, 30.0])
    exact_int = whole.astype(np.int64, casting="same_value")
     
    print("raw dtype:", raw.dtype, raw)
    print("float dtype:", floats.dtype, floats)
    print("truncated int dtype:", truncated.dtype, truncated)
    print("exact int dtype:", exact_int.dtype, exact_int)
     
    try:
        floats.astype(np.int64, casting="same_value")
    except ValueError as error:
        print("strict cast error:", error)

    casting=“same_value” requires NumPy 2.4 or newer. It raises ValueError when rounding, truncation, or integer overflow would change a value.

  2. Run the script and compare each dtype with its printed values.
    $ python array-convert-dtype.py
    raw dtype: <U4 ['1.25' '2.50' '3.75']
    float dtype: float64 [1.25 2.5  3.75]
    truncated int dtype: int64 [1 2 3]
    exact int dtype: int64 [10 20 30]
    strict cast error: could not cast 'same_value' double to long

    The string array becomes float64 first. The default integer cast drops the fractional parts, while casting=“same_value” accepts only the whole-number array.

  3. Verify that the final line reports a strict cast error for the fractional float array.

    That error means the strict conversion path is blocking value-changing casts. Keep the converted result in a separate variable when the original dtype should remain available for review.
    Related: Check views and copies