TypeError:数组dtype('object')和格式说明符('%.18e')之间不匹配

Sim*_*ity 12 python arrays text numpy save

我有以下数组:

X = np.array([image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4])
Run Code Online (Sandbox Code Playgroud)

打印出来的X外观如下:

[array([167, 167, 169, ...,   1,   1,   1], dtype=uint8)
 array([42, 43, 43, ..., 41, 36, 34], dtype=uint8)
 array([0, 0, 0, ..., 0, 0, 0], dtype=uint8)
 array([0, 0, 0, ..., 0, 0, 0], dtype=uint8)]
Run Code Online (Sandbox Code Playgroud)

当我尝试将数据保存为txt时:

X_to_text_file = np.savetxt('x.txt',X)
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

File "/Library/Python/2.7/site-packages/numpy/lib/npyio.py", line 1258, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')
Run Code Online (Sandbox Code Playgroud)

这是为什么?我该如何解决这个问题?

谢谢.

Grr*_*Grr 22

如果没有一些示例数据,复制它有点困难,但这就是我提出的.

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')
Run Code Online (Sandbox Code Playgroud)

正如@Artier指出的那样,在Write对象数组到.txt文件 的接受答案的末尾有一个小片段,指出你可以将数组保存为字符串fmt='%s'.使用这种格式似乎可以解决我的问题(再次,我无法在没有数据样本的情况下完全重新创建您的问题).

np.savetxt('x.txt', arr, fmt='%s')
Run Code Online (Sandbox Code Playgroud)

我想指出,如果你想保存不同的数组,并希望一个位置保持它们savez是非常有用的.

  • fmt='%s' 很有用。谢谢。 (3认同)

hpa*_*ulj 11

In essence savetxt is doing:

for row in your_array:
    print(fmt % tuple(row))
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

%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]
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)