Use the .astype method:

all_data.astype(dtype=[('v1', 'S3'), ('v2', '<i4'), ('v3', '|S30'), ('v4', '<f8'), ('v5', '<f8'), ('v6', '<f8'), ('v7', 'O')])
#rec.array([('GNB', 1980, '-1', 20.0, -1.168689, 0.4619077, None),
#           ('GNB', 1981, '20', -1.185176, 0.4619077, nan, None)], 
#             dtype=[('v1', 'S3'), ('v2', '<i4'), ('v3', 'S30'), ('v4', '<f8'), ('v5', '<f8'), ('v6', '<f8'), ('v7', 'O')])
Answer from root on Stack Overflow
🌐
GitHub
github.com › numpy › numpy › issues › 5762
TypeError: Cannot change data-type for object array · Issue #5762 · numpy/numpy
April 10, 2015 - If I try and read in the array contained in this npy file: https://gist.github.com/astrofrog/8c2d188005f31e0bba36/raw/3065c8fa220a6eaccbff20565d0d520c07e5e7e6/test.npy then try and print out the array, so: import numpy as np array = np.l...
Author   numpy
Discussions

recarray.__getitem__ with field list gives "TypeError: Cannot change data-type for object array." when dtype contains object
This code works for me on numpy 1.6.2 but on 1.7.1 I get an exception, because in the new version numpy.core._internal._index_fields calls ary.view() and this doesn't work on object arrays. imp... More on github.com
🌐 github.com
11
April 17, 2013
TypeError: Cannot change data-type for object array.
Interactive plotting for Python. Contribute to sandialabs/toyplot development by creating an account on GitHub. More on github.com
🌐 github.com
8
July 7, 2015
python - How to change the dtype of a numpy array to 'object'? - Stack Overflow
This is a 2 element array, shape (2,). But it doesn't change the nature of the elements. And there's a potential gotcha - if the element arrays had the same shape, it would have created a 3d array of objects. This is not the right syntax for change the dtype of an array. More on stackoverflow.com
🌐 stackoverflow.com
python - Why can the datatype of an array not be changed inside a loop? - Stack Overflow
The assignment in the loop assigns that new object to the name y. Because of the assignment y no longer points to the array item so the array item is not changed. If you were performing an operation in the loop that modified the item in-place it would work like you expected. ... ... Whereas for i,y ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › pandas-dev › pandas › issues › 21630
Unraisable error with TypeError: Cannot change data-type for object array · Issue #21630 · pandas-dev/pandas
June 25, 2018 - The above code will simultaneously print "ERROR: Cannot change data-type for object array." AND NOT raise an error.
Author   pandas-dev
🌐
GitHub
github.com › numpy › numpy › issues › 3256
recarray.__getitem__ with field list gives "TypeError: Cannot change data-type for object array." when dtype contains object · Issue #3256 · numpy/numpy
April 17, 2013 - This code works for me on numpy 1.6.2 but on 1.7.1 I get an exception, because in the new version numpy.core._internal._index_fields calls ary.view() and this doesn't work on object arrays. import numpy as np ra = np.recarray((2,), dtype...
Author   numpy
🌐
GitHub
github.com › sandialabs › toyplot › issues › 53
TypeError: Cannot change data-type for object array. #53
July 7, 2015 - No fields configured for issues without a type.
Author   sandialabs
🌐
LinuxTut
linuxtut.com › en › 1bb8e77819bd6841e5fa
TypeError: Cannot change data-type for object array.
April 9, 2020 - File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/stride_tricks.py", line 119, in broadcast_arrays zip(args, shapes, strides)] File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/stride_tricks.py", line 32, in as_strided array.dtype = x.dtype TypeError: Cannot change data-type for object array.
🌐
Microsoft Learn
learn.microsoft.com › en-us › office › vba › language › reference › user-interface-help › can-t-change-data-types-of-array-elements
Can't change data types of array elements | Microsoft Learn
ReDim can only be used to change the number of elements in an array. This error has the following cause and solution: You tried to redeclare the data type of an array using ReDim.
Top answer
1 of 1
4

Let's make sure we understand what you are starting with:

In [7]: weights
Out[7]: 
[array([[-2.66665269,  0.        ],
        [-0.36358187,  0.        ],
        [ 1.55058871,  0.        ],
        [ 3.91364328,  0.        ]]), array([[ 0.],
        [ 0.]])]
In [8]: len(weights)
Out[8]: 2
In [9]: weights[0]
Out[9]: 
array([[-2.66665269,  0.        ],
       [-0.36358187,  0.        ],
       [ 1.55058871,  0.        ],
       [ 3.91364328,  0.        ]])
In [10]: weights[0].dtype
Out[10]: dtype('float64')
In [11]: weights[0].shape
Out[11]: (4, 2)

In [13]: weights[1]
Out[13]: 
array([[ 0.],
       [ 0.]])
In [14]: weights[1].dtype
Out[14]: dtype('float64')
In [15]: weights[1].shape
Out[15]: (2, 1)

This is a 2 item list, containing two arrays. Both are 2d float.

First you wrap the whole list in an object array:

In [16]: duh =np.array(weights,dtype='object')
In [17]: duh
Out[17]: 
array([ array([[-2.66665269,  0.        ],
       [-0.36358187,  0.        ],
       [ 1.55058871,  0.        ],
       [ 3.91364328,  0.        ]]),
       array([[ 0.],
       [ 0.]])], dtype=object)

This is a 2 element array, shape (2,). But it doesn't change the nature of the elements. And there's a potential gotcha - if the element arrays had the same shape, it would have created a 3d array of objects.

This is not the right syntax for change the dtype of an array. dtype is not a writable property/attribute.

weights[1].dtype='object'

We can use astype instead:

In [19]: weights[1].astype(object)
Out[19]: 
array([[0.0],
       [0.0]], dtype=object)
In [20]: weights[1]=weights[1].astype(object)
In [21]: weights
Out[21]: 
[array([[-2.66665269,  0.        ],
        [-0.36358187,  0.        ],
        [ 1.55058871,  0.        ],
        [ 3.91364328,  0.        ]]), array([[0.0],
        [0.0]], dtype=object)]

It makes a new array, which we'd have write back into the original list.

Now I can change an element of that 2nd array

In [22]: weights[1][0,0]=None
In [23]: weights
Out[23]: 
[array([[-2.66665269,  0.        ],
        [-0.36358187,  0.        ],
        [ 1.55058871,  0.        ],
        [ 3.91364328,  0.        ]]), array([[None],
        [0.0]], dtype=object)]

When playing games like this you have to pay attention to where you have arrays and where they are lists. And pay attention to the shape and dtype of the arrays. Don't blindly index and hope for the best. Display/print these attributes, or the whole array if it isn't too large.

Find elsewhere
🌐
Quora
quora.com › Can-you-change-data-types-in-an-array
Can you change data types in an array? - Quora
Answer: Yes, but, here be dragons, maybe. If you mean by that, can part of an array be only type and part be another type, please consider either 2 arrays, one for each type, or a structure of some kind. or if you are asking I'd it can be randomly dispersed, please consider using an array of poi...
Top answer
1 of 1
3
In [161]: a = np.zeros(3, dtype={'names':['A','B','C'], 'formats':['int','int','
     ...: float']}) 
     ...: for i in range(len(a)): 
     ...:     a[i] = i 
     ...:                                                                       
In [162]: a                                                                     
Out[162]: 
array([(0, 0, 0.), (1, 1, 1.), (2, 2, 2.)],
      dtype=[('A', '<i8'), ('B', '<i8'), ('C', '<f8')])

define the new dtype:

In [164]: a.dtype.descr                                                         
Out[164]: [('A', '<i8'), ('B', '<i8'), ('C', '<f8')]
In [165]: a.dtype.descr+[('test','O')]                                          
Out[165]: [('A', '<i8'), ('B', '<i8'), ('C', '<f8'), ('test', 'O')]
In [166]: dt= a.dtype.descr+[('test','O')]                                      

new array of right size and dtype:

In [167]: b = np.empty(a.shape, dt)                                             

copy values from a to b by field name:

In [168]: for name in a.dtype.names: 
     ...:     b[name] = a[name] 
     ...:                                                                       
In [169]: b                                                                     
Out[169]: 
array([(0, 0, 0., None), (1, 1, 1., None), (2, 2, 2., None)],
      dtype=[('A', '<i8'), ('B', '<i8'), ('C', '<f8'), ('test', 'O')])

Many of the rf functions do this field by field copy:

rf.recursive_fill_fields(a,b)

rf.append_fields uses this after it initializes it's output array.

In earlier versions a multifield index produced a copy, so expressions like b[list(a.dtype.names)] = a would not work.


I don't know if it's worth trying to figure out what rf.append_fields is doing. Those functions are somewhat old, and not heavily used (note the special import). So it's entirely likely that they have bugs, or edge cases , that don't work. The functions that I've examined function much as I demonstrated - make a new dtype, and result array, and copy data by field name.

In recent releases there have been changes in how multiple fields are accessed. There are some new functions in recfunctions to facilitate working with structured arrays, such as repack_fields.

https://docs.scipy.org/doc/numpy/user/basics.rec.html#accessing-multiple-fields

I don't know if any of that applies to the append_fields problem. I see there's also a section about structured arrays with objects, but I haven't studied that:

https://docs.scipy.org/doc/numpy/user/basics.rec.html#viewing-structured-arrays-containing-objects

In order to prevent clobbering object pointers in fields of numpy.object type, numpy currently does not allow views of structured arrays containing objects.

This line apparently refers to the use of view method. Views created by field indexing, whether single name or multifield lists, are not affected.


The error in append_fields comes from this operation:

In [183]: data = np.array([None,None,None])                                          
In [184]: data                                                                       
Out[184]: array([None, None, None], dtype=object)
In [185]: data.view([('test',object)])                                               
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-185-c46c4464b53c> in <module>
----> 1 data.view([('test',object)])

/usr/local/lib/python3.6/dist-packages/numpy/core/_internal.py in _view_is_safe(oldtype, newtype)
    492 
    493     if newtype.hasobject or oldtype.hasobject:
--> 494         raise TypeError("Cannot change data-type for object array.")
    495     return
    496 

TypeError: Cannot change data-type for object array.

There's no problem creating an compound dtype with object dtypes:

In [186]: np.array([None,None,None], dtype=[('test',object)])                        
Out[186]: array([(None,), (None,), (None,)], dtype=[('test', 'O')])

But I don't see any recfunctions that are capable of joining a and data.


view can be used to change the field names of a:

In [219]: a.view([('AA',int),('BB',int),('cc',float)])                               
Out[219]: 
array([(0, 0, 0.), (1, 1, 1.), (2, 2, 2.)],
      dtype=[('AA', '<i8'), ('BB', '<i8'), ('cc', '<f8')])

but trying to do so for b fails for the same reason:

In [220]: b.view([('AA',int),('BB',int),('cc',float),('d',object)])                  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-220-ab0a6e4dd57f> in <module>
----> 1 b.view([('AA',int),('BB',int),('cc',float),('d',object)])

/usr/local/lib/python3.6/dist-packages/numpy/core/_internal.py in _view_is_safe(oldtype, newtype)
    492 
    493     if newtype.hasobject or oldtype.hasobject:
--> 494         raise TypeError("Cannot change data-type for object array.")
    495     return
    496 

TypeError: Cannot change data-type for object array.

I start with a object dtype array, and try to view with i8 (same size dtype), I get this same error. So the restriction on view of a object dtype isn't limited to structured arrays. The need for such a restriction in the case of object pointer to i8 makes sense. The need for such a restriction in the case of embedding the object pointer in a compound dtype might not be so compelling. It might even be overkill, or just a case of simply playing it safe and simple.

In [267]: x.dtype                                                                    
Out[267]: dtype('O')
In [268]: x.shape                                                                    
Out[268]: (3,)
In [269]: x.dtype.itemsize                                                           
Out[269]: 8
In [270]: x.view('i8')                                                               
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-270-30c78b13cd10> in <module>
----> 1 x.view('i8')

/usr/local/lib/python3.6/dist-packages/numpy/core/_internal.py in _view_is_safe(oldtype, newtype)
    492 
    493     if newtype.hasobject or oldtype.hasobject:
--> 494         raise TypeError("Cannot change data-type for object array.")
    495     return
    496 

TypeError: Cannot change data-type for object array.

Note that the test in line 493 checks the hasobject property of both the new and old dtypes. A more nuanced test might check if both hasobject, but I suspect the logic could get quite complex. Sometimes a simple prohibition is safer (and easier) a complex set of tests.


In further testing

In [283]: rf.structured_to_unstructured(a)                                           
Out[283]: 
array([[ 3.,  3.,  0.],
       [12., 10.,  1.],
       [ 2.,  2.,  2.]])

but trying to do the same on b, or even a subset of its fields produces the familiar error:

rf.structured_to_unstructured(b)
rf.structured_to_unstructured(b[['A','B','C']]) 

I have to first use repack to make a object-less copy:

rf.structured_to_unstructured(rf.repack_fields(b[['A','B','C']])) 
🌐
GitHub
github.com › pandas-dev › pandas › issues › 9336
Problem mixing datetime64 with other types in DataFrame column · Issue #9336 · pandas-dev/pandas
January 22, 2015 - In[255]: df.loc[[0, 1], 'c'] = A.values[:, 1] TypeError: Cannot change data-type for object array. No one assigned ·
Author   pandas-dev
🌐
GitHub
github.com › pandas-dev › pandas › issues › 3217
BUG: change dtype of Series from non-object to object inplace · Issue #3217 · pandas-dev/pandas
March 29, 2013 - see also #3216 , #3386 test in tests/test_series.py (test_update) but cannot be fixed until Series is not longer a ndarray sub-class as numpy cannot handle the float64 to object in-place dtype conversion (which is why the sub-class issue...
Author   pandas-dev
🌐
NumPy
numpy.org › devdocs › reference › arrays.dtypes.html
Data type objects (dtype) — NumPy v2.6.dev0 Manual
This is useful for creating custom structured dtypes, as done in record arrays. This form also makes it possible to specify struct dtypes with overlapping fields, functioning like the ‘union’ type in C. This usage is discouraged, however, and the union mechanism is preferred. Both arguments must be convertible to data-type objects with the same total size.
🌐
W3Schools
w3schools.com › python › numpy › numpy_data_types.asp
NumPy Data Types
The best way to change the data type of an existing array, is to make a copy of the array with the astype() method. The astype() function creates a copy of the array, and allows you to specify the data type as a parameter.
🌐
GeeksforGeeks
geeksforgeeks.org › change-data-type-of-given-numpy-array
Change data type of given numpy array - GeeksforGeeks
August 9, 2021 - Change the dtype of the given object to 'complex128'. Solution : We will use numpy.astype() function to change the data type of the underlying data of the given numpy array.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › change-numpy-array-data-type
Change the Data Type of the Given NumPy Array - GeeksforGeeks
Given a NumPy array whose underlying data is of 'int32' type. Change the data type of the given object to 'float64'.
Published   July 11, 2025
🌐
Reddit
reddit.com › r/php › thoughts on avoiding 'cannot use object as array'?
r/PHP on Reddit: Thoughts on avoiding 'Cannot use object as array'?
August 3, 2025 -

Hello everyone, I'd like to do deep dive on a subject...this morning I encountered the error the subject. Here is the method though the specifics don't matter to me.

public function quantity_limit($item)
{
    $response = 99;
    if (!empty($item->inventory)){
        if ($item->inventory_count < $response){ $response = $item->inventory_count; }
    } elseif (!empty($item['inventory'])){
        if ($item['inventory_count'] < $response){ $response = $item['inventory_count']; }
    }
    return $response;
}

I'd like this method to be able to handle both database rows and class/object representing the same data. Right off the bat, I understand that might be questionable. Here is my logic, most of the time I am working off a single item (product for example) and love having the flexibilty of an object. However, in some situations I am working with a large amount of data (lets say a product search result) and it feels like a lot it's a lot of overhead to generate objects for each row when I'm just displaying basic data.

So, to fix the problem...obviously I can just add is_array() or is_object() tests. I can also check the data at the top of the method and convert it to one format. That is all fine. However I guess I was hoping there were some tricks. I figured it was worth learning/exploring. Really I just wished empty() worked how I expected it to...I'm kind of suprised it doesn't.

Open to all thoughts/ideas. Thanks for your time.

🌐
HDF Forum
forum.hdfgroup.org › hdf5 library › h5py
setting dataset string field results in TypeError - h5py - HDF Forum
March 8, 2021 - I’m using Ubuntu 18.04.5 LTS with python 3.8.0 from apt. I created a fresh virtualenv and pip installed h5py for testing. h5py version info: >>> print(h5py.version.info) Summary of the h5py configuration --------------------------------- h5py 3.2.1 HDF5 1.12.0 Python 3.8.0 (default, Oct 28 2019, 16:14:01) [GCC 8.3.0] sys.platform linux sys.maxsize 9223372036854775807 numpy 1.20.1 cython (built with) 0.29.22 numpy (built against) 1.17.5 HDF5 (built against) 1.12.0 I have a s...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.array.html
pandas.array — pandas 3.0.3 documentation - PyData |
the returned array type doesn’t change as new extension types are added by pandas and third-party libraries · Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the dtype as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data...