Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

However, if it's already a numpy array of strings, there's a better way. Use astype().

import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)
Answer from Joe Kington on Stack Overflow
๐ŸŒ
IONOS
ionos.com โ€บ digital guide โ€บ websites โ€บ web development โ€บ converting python strings to floats
How to convert Python strings to floats - IONOS
January 2, 2025 - If you want to convert a Python string to a float with NumPy, you can use the function numpy.float64().
Discussions

ValueError: could not convert string to float: '' in python numpy
I am new to numpy and have a problem. after running these lines of code I get an error! ValueError: could not convert string to float: '' wb = r"C:\\Users................\df.xls" def create_array(wb): sheet = xlrd.oโ€ฆ More on forum.posit.co
๐ŸŒ forum.posit.co
0
0
August 9, 2022
python - Numpy Convert String to Float when Possible - Stack Overflow
Suppose I have a list mix = numpy.array(['1.', '2.', 'a']) How can I convert string to float when possible, so that I could get: array([1., 2., 'a']) I try to use try / exception with astype(),... More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 10, 2016
python - Numpy converting array from float to strings - Stack Overflow
I have an array of floats that I have normalised to one (i.e. the largest number in the array is 1), and I wanted to use it as colour indices for a graph. In using matplotlib to use grayscale, this More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert numpy, list or float to string in python - Stack Overflow
I'm writing a python function to append data to text file, as shown in the following, The problem is the variable, var, could be a 1D numpy array, a 1D list, or just a float number, I know how to More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Cherry Servers
cherryservers.com โ€บ home โ€บ blog โ€บ python โ€บ how to convert string to float in python (6 different ways)
How to Convert String to Float in Python (6 Different Ways) | Cherry Servers
July 25, 2024 - There are a few methods to convert string to float in Python. However, we will focus only on the following methods within this article. Using the float() function. Using the Decimal() function. Using the โ€˜astโ€™ Module for Literal Evaluation.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ using-numpy-to-convert-array-elements-to-float-type
Using NumPy to Convert Array Elements to Float Type - GeeksforGeeks
July 15, 2025 - Explanation: Here, a string array a is converted to a float array res using astype(float), creating a new array without modifying the original. NumPy allows you to define the type of elements directly during the creation of the array using the ...
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ python string to float, float to string
Python String to float, float to String - AskPython
February 16, 2023 - Python provides us with the built-in float() method to convert the data type of input from String to float. ... inp = '99.23' print("Input string:\n",inp) opt = float(inp) print('Input value after converting it to float type:\n',opt) ...
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ string-to-float-python
6 Ways to Convert String to Float in Python | FavTutor
August 31, 2021 - If you want to convert a string into float using NumPy, the first step will be to import the NumPy library using โ€œimport NumPy as np.โ€ Later, you can use the โ€œastypeโ€ method, an in-build method used to convert the string to a floating-point ...
๐ŸŒ
YouTube
youtube.com โ€บ codegpt
convert string to float python numpy - YouTube
Instantly Download or Run the code at https://codegive.com tutorial: converting string to float in python with numpyin python, particularly when working wit...
Published ย  March 16, 2024
Views ย  2
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ how to convert string to float in python?
Convert String to Float in Python - Scaler Topics
May 5, 2022 - For converting the list of strings ... have to iterate the string list and take the values one by one and then convert the string values to the floating values and then append all the float values to the floating value list...
Find elsewhere
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.fromstring.html
numpy.fromstring โ€” NumPy v2.4 Manual
June 22, 2021 - A string containing the data. ... The data type of the array; default: numpy.float64. For binary input data, the data must be in exactly this format.
๐ŸŒ
Posit Community
forum.posit.co โ€บ general
ValueError: could not convert string to float: '' in python numpy - General - Posit Community
August 9, 2022 - I am new to numpy and have a problem. after running these lines of code I get an error! ValueError: could not convert string to float: '' wb = r"C:\\Users................\df.xls" def create_array(wb): sheet = xlrd.open_workbook(wb).sheet_by_index(0) wb_list = [sheet.row_values(i) for i in range(sheet.nrows)] return np.array (wb_list) arr = create_array(wb) df = arr[1:, 1:] df pid =0 age = 1 BMI = 2 PA_Score_Cat = 3 WS_Q = 4 Residence =5 adata = df[:, age].astype(float) def stat_calc...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-ways-to-convert-array-of-strings-to-array-of-floats
Python | Ways to convert array of strings to array of floats - GeeksforGeeks
July 11, 2025 - Here is the approach to convert an array of strings from Python to an array float using astype(). It is used to change the datatype of a series. if a column could be imported as a string but to do operations we have to convert it into a float, ...
๐ŸŒ
Medium
medium.com โ€บ @Doug-Creates โ€บ convert-string-to-float-or-int-in-python-0d93ce89d7b1
Convert String to Float or Int in Python | by Doug Creates | Medium
March 24, 2024 - # Import necessary libraries from sklearn.preprocessing import StandardScaler import numpy as np # Example data: Strings that could be converted to float or int string_values = ['3.14', '100', '0.99', '42', 'not_a_number', '5.0'] # Preprocess: Attempt to convert strings to float, handle errors float_values = [] for value in string_values: try: # Attempt to convert each string to a float float_values.append(float(value)) except ValueError: # If conversion fails, print an error message and skip the value print(f'Could not convert {value} to float.') continue # Convert the list of floats to a num
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ generated โ€บ numpy.fromstring.html
numpy.fromstring โ€” NumPy v2.5.dev0 Manual
A string containing the data. ... The data type of the array; default: numpy.float64. For binary input data, the data must be in exactly this format.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.fromstring.html
numpy.fromstring โ€” NumPy v2.2 Manual
A string containing the data. ... The data type of the array; default: float. For binary input data, the data must be in exactly this format.
Top answer
1 of 5
45

You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.

The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'.

A accurate string representation of a floating point number produces a variable length string.

Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.

If you use x.astype('str'), it will always convert things to an array of strings of length 1.

For example, using x = np.array(1.344566), x.astype('str') yields '1'!

You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array.

For example, use x.astype('|S10') to convert the array to strings of length 10.

Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...

2 of 5
25

If you have an array of numbers and you want an array of strings, you can write:

strings = ["%.2f" % number for number in numbers]

If your numbers are floats, the array would be an array with the same numbers as strings with two decimals.

>>> a = [1,2,3,4,5]
>>> min_a, max_a = min(a), max(a)
>>> a_normalized = [float(x-min_a)/(max_a-min_a) for x in a]
>>> a_normalized
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> a_strings = ["%.2f" % x for x in a_normalized]
>>> a_strings
['0.00', '0.25', '0.50', '0.75', '1.00']

Notice that it also works with numpy arrays:

>>> a = numpy.array([0.0, 0.25, 0.75, 1.0])
>>> print ["%.2f" % x for x in a]
['0.00', '0.25', '0.50', '0.75', '1.00']

A similar methodology can be used if you have a multi-dimensional array:

new_array = numpy.array(["%.2f" % x for x in old_array.reshape(old_array.size)])
new_array = new_array.reshape(old_array.shape)

Example:

>>> x = numpy.array([[0,0.1,0.2],[0.3,0.4,0.5],[0.6, 0.7, 0.8]])
>>> y = numpy.array(["%.2f" % w for w in x.reshape(x.size)])
>>> y = y.reshape(x.shape)
>>> print y
[['0.00' '0.10' '0.20']
 ['0.30' '0.40' '0.50']
 ['0.60' '0.70' '0.80']]

If you check the Matplotlib example for the function you are using, you will notice they use a similar methodology: build empty matrix and fill it with strings built with the interpolation method. The relevant part of the referenced code is:

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        colors[x, y] = colortuple[(x + y) % len(colortuple)]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0, antialiased=False)
๐ŸŒ
PhoenixNAP
phoenixnap.com โ€บ home โ€บ kb โ€บ devops and development โ€บ python: string to float conversion
Python: String to Float Conversion | phoenixNAP KB
November 17, 2025 - import numpy as np arr = np.array(["1.1", "2.2", "3.3"]) float_arr = arr.astype(float) print(float_arr) ... NumPy's conversion methods are optimized for performance and can handle bulk operations much faster than loops or comprehensions. Conversion errors usually occur due to invalid formatting, missing values, or unexpected characters in the string. ... Invalid numeric format. If the string contains letters or symbols that are not part of a valid number, Python raises a ValueError. Validate or clean the input before converting.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
July 10, 2025 - Learn how to convert strings to floats in Python using float(). Includes syntax, examples, error handling tips, and real-world use cases for data parsing.