TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')

我只是一个虾纸丫 提交于 2019-12-02 23:46:15

It's a little difficult to duplicate this without some example data, but here is what I came up with.

arr = np.array([np.array([1,2,3]), np.array([1,2,3,4])])
arr
array([array([1, 2, 3]), array([1, 2, 3, 4])], dtype=object)
np.savetxt('x.txt', arr)
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')

As pointed out by @Artier there is a little snippet at the end of the accepted answer in Write object array to .txt file that points out you can just save the array as a string with fmt='%s'. Using this format seems to solve the problem for me (again I can't recreate your issue exactly without a sample of data).

np.savetxt('x.txt', arr, fmt='%s')

I would point out that if you are looking to save disparate arrays and want a single location to keep them savez is very useful.

In essence savetxt is doing:

for row in your_array:
    print(fmt % tuple(row))

where fmt is constructed your fmt parameter (or the default one) and the number of columns, and the delimiter.

You have a 1d array of objects (arrays). So the write/print will be

 print(fmt % tuple(element))

%s is the only format that can handle an array (or other general object).

savetxt is meant to be used with 2d numeric arrays, the kind of thing that will produce need csv columns. Trying to use it on other things like this object array is going to give you headaches.

In [2]: A = np.empty((3,),dtype=object)
In [3]: A[:] = [np.arange(3),np.arange(1,4), np.arange(-3,0)]
In [4]: A
Out[4]: array([array([0, 1, 2]), array([1, 2, 3]), array([-3, -2, -1])], dtype=object)

In [6]: np.savetxt('test',A,fmt='%s')
In [7]: cat test
[0 1 2]
[1 2 3]
[-3 -2 -1]

Iterating on a 1d array it must be skipping the tuple. In any case the best you can do is a %s format. Otherwise write your own custom file writer. savetxt isn't anything special or powerful.

In [9]: for row in A:
   ...:     print('%s'%row)  
[0 1 2]
[1 2 3]
[-3 -2 -1]

I had the same error message, and it appeared that the problem was with arrays having different length. So you need to be sure to give the np.savetxt arrays of equal length.

For me error occurred when using an older conda environment which had numpy=1.13.1.

Updating to numpy=1.16.2 gave no such errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!