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
🌐
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 - Converting array elements to float type in Python means transforming each item in an array into a floating-point number. For example, an array like ["1.1", "2.2", "3.3"] contains string representations of numbers, which need to be converted ...
🌐
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 loop and float functions. Create an empty array to store the converted floats. Loop through each element of the input array and convert the current element ...
Discussions

python - How to convert an array of strings to an array of floats in numpy? - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... 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 ... More on stackoverflow.com
🌐 stackoverflow.com
How to cast binary array to float array?
Hi! I am trying to read some data coming over serial com port. The data comes as a raw binary float array. Python’ serial module reads the data as string. Now, I need to convert this string to float array. I had been rea… More on discuss.python.org
🌐 discuss.python.org
0
0
February 20, 2024
Is there a way to define a float array in Python? - Stack Overflow
For my astronomy homework, I need to simulate the elliptical orbit of a planet around a sun. To do this, I need to use a for loop to repeatedly calculate the motion of the planet. However, every ti... More on stackoverflow.com
🌐 stackoverflow.com
Convert list or numpy array of single element to float in python - Stack Overflow
In either case, the list/array has a single element (always). I just need to return a float. ... I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way. More on stackoverflow.com
🌐 stackoverflow.com
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-7.php
NumPy: Array converted to a float type - w3resource
August 29, 2025 - Write a NumPy program to convert an array to a floating type. ... # Importing the NumPy library with an alias 'np' import numpy as np # Defining a Python list 'a' containing integers a = [1, 2, 3, 4] # Printing the original array 'a' print("Original array") print(a) # Converting the array 'a' to a NumPy array of type float using asfarray() x = np.asfarray(a) # Printing the array 'x' after converting to a float type print("Array converted to a float type:") print(x)
🌐
Python.org
discuss.python.org › python help
How to cast binary array to float array? - Python Help - Discussions on Python.org
February 20, 2024 - Hi! I am trying to read some data coming over serial com port. The data comes as a raw binary float array. Python’ serial module reads the data as string. Now, I need to convert this string to float array. I had been rea…
🌐
IncludeHelp
includehelp.com › python › convert-list-or-numpy-array-of-single-element-to-float.aspx
Python - Convert list or NumPy array of single element to float
December 23, 2023 - # Import numpy import numpy as np # Creating a numpy array arr = np.array([4]) # Display original array print("Original Array:\n", arr, "\n") # Converting to float res = float(arr) # Display result print("Result:\n", res) ''' # YOU CAN ALSO USE THIS...
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert a numpy array from integers to floats
5 Best Ways to Convert a NumPy Array from Integers to Floats - Be on the Right Side of Change
February 20, 2024 - Specifically, users often face the need to transform an array of integers into an array of floats to allow for more precise calculations. For example, converting the NumPy integer array np.array([1, 2, 3]) to a float array np.array([1.0, 2.0, 3.0]).
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
November 8, 2024 - ... import numpy as np data = ... conversion:", bool_data) Explain Code · In this example, floating-point numbers are converted to integers and booleans....
🌐
Reddit
reddit.com › r/learnprogramming › [python] | working with float array
r/learnprogramming on Reddit: [Python] | Working with float array
September 29, 2021 -

Someone tell me wtf is going on with my output :(

Why doesn't it just show 1.1 in the array

What is the difference between float and double in simplest terms possible. Can you give an example to distinguish between them?

import array

a1 = array.array('f', [1.1])
a2 = array.array('d', [1.1])
print(a1)
print(a2)

Output:

array('f', [1.100000023841858])
array('d', [1.1])
🌐
TutorialsPoint
tutorialspoint.com › convert-masked-array-elements-to-float-type-in-numpy
Convert Masked Array elements to Float Type in Numpy
February 22, 2022 - import numpy as np import numpy.ma ... method arr = np.array([30]) print("Array...", arr) print(" Array type...", arr.dtype) # Get the dimensions of the Array print(" Array Dimensions...",arr.ndim) # Create a masked array maskArr = ma.masked_array(arr, mask =[False]) print(" Our Masked Array ", maskArr) print(" Our Masked Array type... ", maskArr.dtype) # Get the dimensions of the Masked Array print(" Our Masked Array Dimensions... ",maskArr.ndim) # To convert masked array to float type, use the ma.MaskedArra...
🌐
TutorialsPoint
tutorialspoint.com › python-ways-to-convert-array-of-strings-to-array-of-floats
Python - Ways to convert array of strings to array of floats
August 6, 2020 - String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes. ... # array of strings to array of floats using astype import numpy as np # initialising array ini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial array print ("initial array", str(ini_array)) # conerting to array of floats # using np.astype res = ini_array.astype(np.float) # printing final result prin
Top answer
1 of 3
23

Generally your idea of trying to apply astype to each column is fine.

In [590]: X[:,0].astype(int)
Out[590]: array([1, 2, 3, 4, 5])

But you have to collect the results in a separate list. You can't just put them back in X. That list can then be concatenated.

In [601]: numlist=[]; obj_ind=[]

In [602]: for ind in range(X.shape[1]):
   .....:     try:
   .....:         x = X[:,ind].astype(np.float32)
   .....:         numlist.append(x)
   .....:     except:
   .....:         obj_ind.append(ind)

In [603]: numlist
Out[603]: [array([ 3.,  4.,  5.,  6.,  7.], dtype=float32)]

In [604]: np.column_stack(numlist)
Out[604]: 
array([[ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.]], dtype=float32)

In [606]: obj_ind
Out[606]: [1]

X is a numpy array with dtype object:

In [582]: X
Out[582]: 
array([[1, 'A'],
       [2, 'A'],
       [3, 'C'],
       [4, 'D'],
       [5, 'B']], dtype=object)

You could use the same conversion logic to create a structured array with a mix of int and object fields.

In [616]: ytype=[]

In [617]: for ind in range(X.shape[1]):
    try:                        
        x = X[:,ind].astype(np.float32)
        ytype.append('i4')
    except:
        ytype.append('O')       

In [618]: ytype
Out[618]: ['i4', 'O']

In [620]: Y=np.zeros(X.shape[0],dtype=','.join(ytype))

In [621]: for i in range(X.shape[1]):
    Y[Y.dtype.names[i]] = X[:,i]

In [622]: Y
Out[622]: 
array([(3, 'A'), (4, 'A'), (5, 'C'), (6, 'D'), (7, 'B')], 
      dtype=[('f0', '<i4'), ('f1', 'O')])

Y['f0'] gives the the numeric field.

2 of 3
2

I think this might help

def func(x):
  a = None
  try:
    a = x.astype(float)
  except:
    # x.name represents the current index value 
    # which is column name in this case
    obj.append(x.name) 
    a = x
  return a

obj = []
new_df = df.apply(func, axis=0)

This will keep the object columns as such which you can use later.

Note: While using pandas.DataFrame avoid using iteration using loop as this much slower than performing the same operation using apply.

Top answer
1 of 8
28

Nasty little problem... I have been fooling around with this toy example:

>>> arr = np.array([['one', [1, 2, 3]],['two', [4, 5, 6]]], dtype=np.object)
>>> arr
array([['one', [1, 2, 3]],
       ['two', [4, 5, 6]]], dtype=object)

My first guess was:

>>> np.array(arr[:, 1])
array([[1, 2, 3], [4, 5, 6]], dtype=object)

But that keeps the object dtype, so perhaps then:

>>> np.array(arr[:, 1], dtype=float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.

You can normally work around this doing the following:

>>> np.array(arr[:, 1], dtype=[('', float)]*3).view(float).reshape(-1, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a readable buffer object

Not here though, which was kind of puzzling. Apparently it is the fact that the objects in your array are lists that throws this off, as replacing the lists with tuples works:

>>> np.array([tuple(j) for j in arr[:, 1]],
...          dtype=[('', float)]*3).view(float).reshape(-1, 3)
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

Since there doesn't seem to be any entirely satisfactory solution, the easiest is probably to go with:

>>> np.array(list(arr[:, 1]), dtype=float)
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

Although that will not be very efficient, probably better to go with something like:

>>> np.fromiter((tuple(j) for j in arr[:, 1]), dtype=[('', float)]*3,
...             count=len(arr)).view(float).reshape(-1, 3)
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])
2 of 8
13

Based on Jaime's toy example I think you can do this very simply using np.vstack():

arr = np.array([['one', [1, 2, 3]],['two', [4, 5, 6]]], dtype=np.object)
float_arr = np.vstack(arr[:, 1]).astype(np.float)

This will work regardless of whether the 'numeric' elements in your object array are 1D numpy arrays, lists or tuples.

🌐
IQCode
iqcode.com › code › python › string-array-to-float-array-python
string array to float array python Code Example
Log in, to leave a comment · 4.13 · 8 · Menme1 100 points · import numpy as np x = np.array(['1.1', '2.2', '3.3']) y = x.astype(np.float) print(y) # Output : [1.1, 2.2, 3.3] Thank you! 8 · 4.13 (8 Votes) 0 · Are there any code examples left? Find Add Code snippet · New code examples in category Python ·
🌐
Python Examples
pythonexamples.org › python-create-a-float-array
Python - Create a Float Array
In the following program, we create an empty float array my_array, and then add some float values to this array.
🌐
Educative
educative.io › answers › how-to-convert-data-types-of-arrays-using-numpy-in-python
How to convert data types of arrays using NumPy in Python
Line 4: We use the array() method to create a float type of the array and assign it to a variable called my_array.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.4 Manual
June 22, 2021 - Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.