Python - Ways to convert array of strings to array of floats

When working with numerical data, you often need to convert arrays of string numbers to floating-point arrays for mathematical operations. NumPy provides several efficient methods to perform this conversion.

Using astype() Method

The astype() method is the most common way to convert data types in NumPy arrays ?

import numpy as np

# Create array of string numbers
string_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("Initial array:", string_array)

# Convert to array of floats using astype
float_array = string_array.astype(np.float64)
print("Final array:", float_array)
print("Data type:", float_array.dtype)
Initial array: ['1.1' '1.5' '2.7' '8.9']
Final array: [1.1 1.5 2.7 8.9]
Data type: float64

Using fromstring() Method

The fromstring() method creates a new array from string data with a specified separator ?

import numpy as np

# Create array of string numbers
string_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("Initial array:", string_array)

# Join strings with comma separator
joined_string = ', '.join(string_array)
print("Joined string:", joined_string)

# Convert using fromstring
float_array = np.fromstring(joined_string, dtype=np.float64, sep=', ')
print("Final array:", float_array)
Initial array: ['1.1' '1.5' '2.7' '8.9']
Joined string: 1.1, 1.5, 2.7, 8.9
Final array: [1.1 1.5 2.7 8.9]

Using asarray() Method

The asarray() method converts input to an array with specified data type ?

import numpy as np

# Create array of string numbers
string_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("Initial array:", string_array)

# Convert using asarray with float64 dtype
float_array = np.asarray(string_array, dtype=np.float64)
print("Final array:", float_array)
print("Array shape:", float_array.shape)
Initial array: ['1.1' '1.5' '2.7' '8.9']
Final array: [1.1 1.5 2.7 8.9]
Array shape: (4,)

Comparison of Methods

Method Best For Performance Memory Usage
astype() Direct type conversion Fast Creates new array
fromstring() String parsing with separators Moderate Creates new array
asarray() Flexible array creation Fast May reuse existing data

Conclusion

Use astype() for simple type conversions as it's the most straightforward method. Choose fromstring() when parsing delimited string data, and asarray() for flexible array creation with type specification.

Updated on: 2026-03-25T09:18:29+05:30

806 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements