numpy
array conversion
strings to floats
python programming
data manipulation

How to convert an array of strings to an array of floats in numpy?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting a NumPy array of strings into floating-point values is a common cleanup step after reading CSV files, command-line input, or loosely typed JSON data. The conversion itself is simple, but real datasets often contain whitespace, empty strings, or invalid numeric text that need deliberate handling.

The practical goal is to turn text into a numeric dtype without losing control over bad rows. In NumPy, the usual tools are np.array, np.asarray, and astype.

The Straightforward Conversion

If every element already contains a valid numeric string, the direct solution is astype(float):

python
1import numpy as np
2
3raw = np.array(["1.5", "2.75", "3.0", "4.125"])
4values = raw.astype(float)
5
6print(values)
7print(values.dtype)

This works because NumPy applies the conversion element by element and produces a new array with a floating-point dtype. In most cases, float becomes float64.

If the source is a regular Python list instead of a NumPy array, you can convert during array creation:

python
1import numpy as np
2
3values = np.array(["10", "20.5", "30.25"], dtype=float)
4print(values)

That avoids creating an intermediate string array.

np.asarray Versus np.array

If your input may already be a NumPy array, np.asarray is slightly more conservative because it reuses the existing array when possible:

python
1import numpy as np
2
3raw = ["5.5", "6.5", "7.5"]
4arr = np.asarray(raw)
5values = arr.astype(np.float32)
6
7print(values)
8print(values.dtype)

Use this when you want array semantics but do not need to force an unconditional copy at creation time.

Handling Whitespace And Missing Values

Real data is rarely clean. Strings may contain leading spaces, trailing newlines, or blank entries. Stripping the text first makes conversion more reliable:

python
1import numpy as np
2
3raw = np.array([" 1.0", "2.5 ", " 3.75 "])
4clean = np.char.strip(raw)
5values = clean.astype(float)
6
7print(values)

Blank strings are a different problem because astype(float) will raise ValueError. If you want missing values to become np.nan, normalize them explicitly:

python
1import numpy as np
2
3raw = np.array(["1.0", "", "3.5", "N/A"])
4clean = np.where((raw == "") | (raw == "N/A"), "nan", raw)
5values = clean.astype(float)
6
7print(values)

That pattern is useful when missing numeric data is expected and downstream code can tolerate NaN values.

When Input May Be Invalid

If some entries may contain invalid text such as abc, fail-fast behavior from astype is often desirable because it surfaces bad input immediately. Still, there are cases where you want a controlled fallback. One clear approach is a small parser function:

python
1import numpy as np
2
3
4def safe_float(text):
5    try:
6        return float(text)
7    except ValueError:
8        return np.nan
9
10
11raw = np.array(["4.5", "bad", "6.75"])
12values = np.array([safe_float(item) for item in raw], dtype=float)
13print(values)

This uses a Python loop, so it is not as fast as a pure vectorized conversion, but it is readable and handles messy input well.

Choosing The Right Float Type

By default, float gives you double precision. If memory matters and single precision is enough, request np.float32 explicitly:

python
1import numpy as np
2
3raw = np.array(["1.1", "2.2", "3.3"])
4values = raw.astype(np.float32)
5print(values.dtype)

This matters when you convert millions of values or prepare arrays for machine learning frameworks that commonly use float32.

Common Pitfalls

A common mistake is assuming astype(float) modifies the original array in place. It returns a new array. If you forget to assign the result, the source remains a string array.

Another pitfall is ignoring whitespace and sentinel values such as N/A, null, or empty strings. Clean those cases before conversion or the entire operation will fail.

A third issue is using Python float conversion in a manual loop for clean data that NumPy could convert directly. That works, but it gives up much of NumPy's convenience and performance without adding any benefit.

Summary

  • Use astype(float) when every string is already a valid number.
  • Use dtype=float during array creation when you do not need an intermediate string array.
  • Clean whitespace and placeholder values before conversion.
  • Map missing or invalid entries to np.nan if downstream code can handle them.
  • Pick np.float32 or np.float64 deliberately based on precision and memory needs.

Course illustration
Course illustration

All Rights Reserved.