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.]])
Answer from Jaime on Stack Overflow
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.

🌐
IncludeHelp
includehelp.com › python › convert-a-numpy-2d-array-with-object-dtype-to-a-regular-2d-array-of-floats.aspx
Python - Convert a NumPy 2D array with object dtype to a regular 2D array of floats
April 4, 2023 - Secondly, we can directly use vstack() method on the extracted column which will stack all the lists vertically and we can define the data type as a float without any error. ... # Import numpy import numpy as np # Creating an array arr = np.array([['one', [1, 2, 3]],['two', [4, 5, 6]]], dtype='O') ...
🌐
YouTube
youtube.com › watch
how to convert dtype object to float in python
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
🌐
GeeksforGeeks
geeksforgeeks.org › using-numpy-to-convert-array-elements-to-float-type
Using NumPy to Convert Array Elements to Float Type - GeeksforGeeks
December 21, 2023 - Original longdouble array: [3.14159265]Converted float array using astype(): [3.14159265]Converted float array using new array creation: [3.14159265] We can also specify the data type during array creation using the dtype parameter. This method is particularly useful when creating a new array with a specific data type. ... import numpy as np # Example NumPy array (integer) integer_array = np.array(["1.1", "2.2", "3.3", "4.4"]) # Convert to float specifying dtype float_array = np.array(integer_array, dtype=float) print("Original Array (Integer):", integer_array) print("Converted Array (Float):", float_array)
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5 Manual
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.
Top answer
1 of 2
2

131.199997,1.31199997e+02 are equivalent displays of the same number. They are both 'normal floats'.

In:

array([[131.199997, 137.149994, 131.199997, 136.320007, 117.08859299999999,
        615015],
       [135.199997, 136.570007, 134.330002, 135.639999, 116.504501, 352835],
       [131.419998, 133.5, 130.759995, 131.779999, 113.18906399999999,
        209805]], dtype=object)

each element is a Python float, and is formatted individually, regardless of the value. Note how some strings are long, other much short.

In:

a = a.astype('float64')                # converting to `float64`
a
array([[  1.31199997e+02,   1.37149994e+02,   1.31199997e+02,
          1.36320007e+02,   1.17088593e+02,   6.15015000e+05],
       [  1.35199997e+02,   1.36570007e+02,   1.34330002e+02,
          1.35639999e+02,   1.16504501e+02,   3.52835000e+05],
       [  1.31419998e+02,   1.33500000e+02,   1.30759995e+02,
          1.31779999e+02,   1.13189064e+02,   2.09805000e+05]])

the array is displayed as a whole, using a format that will work equally well for the smaller values (1e2, 100) and the larger ones (1e5, 100000). With this format it use neat columns, show the 2d array structure.

While you can control how numpy displays such an array, it does not change the underlying numeric values. And for fast numpy calculations, you want this numeric dtype, not the object one.

Try df.sample(3).values[:,1:-1]. That should just be the float values that are all around 100. It's the last integer column with values like 209805 that's triggering the scientific notation.

Better yet, select the columns from the dataframe, "Open,High,Low,Close,Adj Close" before applying .values. Those are all float64 dtype, and the resulting array will have that dtype as well. Select the integer volume column separately. You are already treating the string/object date column separately.

Try:

a = df[df.columns[1:-1]].sample().values
2 of 2
1

Try adding:

np.set_printoptions(suppress=True)

As the first line under import numpy as np.

Top answer
1 of 3
2

Lets take as the starting point a list of lists or equivalently an object array of lists:

A = [[], [], [], [1,2,1], [], [2, 2, 0, 0], []]
A = array([[], [], [], [1,2,1], [], [2, 2, 0, 0], []], dtype=object)

If the sublists were all the same length, np.array([...]) would give you a 2d array, one row for each sublist, and columns matching their common length. But since they are unequal in length, it can only make it a 1d array, where each element is a pointer to one of these sublists - i.e. dtype=object.

I can imagine 2 ways of constructing a 2d array:

  • pad each sublist to a common length
  • insert each sublist into an empty array of the appropriate size.

Basically it requires common Python iteration; it's not a common enough task to have a wiz-bang numpy function.

For example:

In [346]: n=len(A)
In [348]: m=max([len(x) for x in A])
In [349]: AA=np.zeros((n,m),int)
In [350]: for i,x in enumerate(A):
   .....:     AA[i,:len(x)] = x
In [351]: AA
Out[351]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [1, 2, 1, 0],
       [0, 0, 0, 0],
       [2, 2, 0, 0],
       [0, 0, 0, 0]])

To get a sparse matrix:

In [352]: from scipy import sparse
In [353]: MA=sparse.coo_matrix(AA)
In [354]: MA
Out[354]: 
<7x4 sparse matrix of type '<class 'numpy.int32'>'
    with 5 stored elements in COOrdinate format>

Nothing magical, just straight forward sparse matrix construction. I suppose you could bypass the dense matrix

There is a list-of-lists sparse format that looks a bit like your data.

In [356]: Ml=MA.tolil()

In [357]: Ml.rows
Out[357]: array([[], [], [], [0, 1, 2], [], [0, 1], []], dtype=object)

In [358]: Ml.data
Out[358]: array([[], [], [], [1, 2, 1], [], [2, 2], []], dtype=object)

Conceivably you could construct an empty sparse.lil_matrix((n,m)) matrix, and set it's .data attribute directly. But you'd also have to calculate the rows attribute.

You could also look at the data, row. col attributes of the coo format matrix, and decide it would be easy to construct the equivalent from your A list of lists.

One way or other you have to decide how the non-zero rows get padded to the full length.

2 of 3
0

This:

array = numpy.array ( [ x['feature1'] for x in ver ] )

Or you need to be more clear in your example...

Find elsewhere
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.

🌐
w3resource
w3resource.com › python-exercises › numpy › basic › numpy-basic-exercise-41.php
NumPy: Convert numpy dtypes to native python types - w3resource
August 28, 2025 - This process ensures compatibility between NumPy arrays and standard Python operations by enabling seamless data type conversions. ... # Importing the NumPy library with an alias 'np' import numpy as np # Printing a message indicating conversion from numpy.float32 to Python float print("numpy.float32 to python float") # Creating a numpy.float32 value 'x' initialized to 0 x = np.float32(0) # Printing the type of 'x' print(type(x)) # Extracting the Python float value from the numpy.float32 'x' using the item() method pyval = x.item() # Printing the type of the extracted Python float value 'pyval' print(type(pyval))
Top answer
1 of 13
574

Use val.item() to convert most NumPy values to a native Python type:

import numpy as np

# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval))         # <class 'float'>

# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item())  # <class 'int'>
type(np.int16(0).item())   # <class 'int'>
type(np.cfloat(0).item())  # <class 'complex'>
type(np.datetime64(0, 'D').item())  # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item())  # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...

(A related method np.asscalar(val) was deprecated with 1.16, and removed with 1.23).


For the curious, to build a table of conversions of NumPy array scalars for your system:

for name in dir(np):
    obj = getattr(np, name)
    if hasattr(obj, 'dtype'):
        try:
            if 'time' in name:
                npn = obj(0, 'D')
            else:
                npn = obj(0)
            nat = npn.item()
            print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
        except:
            pass

There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble and longfloat. These need to be converted to their nearest NumPy equivalent before using .item().

2 of 13
45

If you want to convert (numpy.array OR numpy scalar OR native type OR numpy.darray) TO native type you can simply do :

converted_value = getattr(value, "tolist", lambda: value)()

tolist will convert your scalar or array to python native type. The default lambda function takes care of the case where value is already native.

🌐
FEniCS Project
fenicsproject.discourse.group › general
Converting dolfin vector dtype object to float - General - FEniCS Project
March 9, 2023 - I am getting output in object datatype. I wanted float data output, but that gives “ValueError: setting an array element with a sequence” error. The extract of code is shown below W = FunctionSpace(mesh, MixedElement([Ve, Re])) dv = TrialFunction(W) w=Function(W) (v, lamb) = split(w) dx = Measure('dx')(subdomain_data=subdomains) def eps(v): return as_vector([0,v[1].dx(0),v[1].dx(0),v[1].dx(0),v[1].dx(0),v[0].dx(0)]) lmbda=2*10^9 mu=3*10^9 C1=2*lmbda+mu C=Constant([(C1,lmbda,lmbda,0,0,0),(l...
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-7.php
NumPy: Array converted to a float type - w3resource
August 29, 2025 - Transform a mixed-type numeric list into a float array and check that all elements are decimals. Implement a conversion function that takes an array and a target dtype, then confirm the new type with type().
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: astype() to change dtype of an array | note.nkmk.me
February 4, 2024 - The object type is a special data type that stores pointers to Python objects. This means that the actual data for each element is stored in a separate memory space, enabling an ndarray to hold pointers to data of different types. a_object = np.array([1, 0.1, 'abc'], dtype=object) print(a_object) # [1 0.1 'abc'] print(a_object.dtype) # object print(type(a_object[0])) print(type(a_object[1])) print(type(a_object[2])) # <class 'int'> # <class 'float'> # <class 'str'> source: numpy_dtype.py ·
🌐
Sololearn
sololearn.com › en › Discuss › 2165723 › how-to-convert-data-type-object-to-float-decimal
How to convert data type: Object to Float/Decimal | Sololearn: Learn to code for FREE!
Hello. I tried float(), to_numeric(), convert_object, astype() but still can't make operations from column A and Column B of a Dataframe. How can I convert such datatype
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › change-numpy-array-data-type
Change the Data Type of the Given NumPy Array - GeeksforGeeks
As we can see in the output, the current data type of the given array object is 'int32'. Now we will change this to 'float64' type. Python3 · # change the dtype to 'float64' arr = arr.astype('float64') print(arr) # print the data type print(arr.dtype) Output : Given a NumPy array whose underlying data is of 'int32' type.
Published: July 11, 2025
🌐
Stack Overflow
stackoverflow.com › questions › 32491842 › how-to-convert-from-a-dtypeo-to-a-dtypefloat-in-numpy
python - How to convert from a dtype('o') to a dtype(float) in numpy? - Stack Overflow
I'm looking for a way to read this csv into python 2.7 and turn it into a (3,22000) array. For some reason I haven't been able to do it, no matter which way i try, I either get a groupn of strings in an array that i cant convert or an array seen below that won't convert to floats or allow computations to be done on them. Any help would be appreciated. Thanks · For the record it says the shape is (22000,), which I'm unsure about also. CopyIn [126]: import csv import numpy as np with open("Data.csv") as sd: ri = [] dv = [] for row in csv.reader(sd): if row != ["ccx","ccy","ccz","cellVolumes","Cell Type"]: nrow = [] for val in row[0:3]: val = float(val) nrow.append(val) ri.append(nrow) nrow = [] for val in row[3:4]: val = float(val) nrow.append(val) dv.append(nrow) ri = np.array(ri) ri
🌐
Arab Psychology
scales.arabpsychology.com › home › how do i convert an object to a float in pandas?
How Do I Convert An Object To A Float In Pandas?
November 29, 2025 - import pandas as pd #create DataFrame ... points object assists int64 dtype: object · The following code shows how to use the astype() function to convert the points column in the DataFrame from an object to a float...