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

2024-09-20 03:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数组:

X = np.array([image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4])

打印出来的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)]

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

X_to_text_file = np.savetxt('x.txt',X)

我得到以下信息:

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')

为什么?我怎样才能解决这个问题?

谢谢。


Tags: to数据imagetxtformatnp数组array
3条回答

实际上savetxt正在做:

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

其中fmt是由fmt参数(或默认参数)和列数以及分隔符构造的。

你有一个1d数组的对象(数组)。所以写/印

 print(fmt % tuple(element))

%s是唯一可以处理数组(或其他常规对象)的格式。

savetxt用于二维数字数组,这类数组将产生需要csv列。尝试在其他事情上使用它,比如这个对象数组,会让你头疼。

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]

迭代1d数组时,它必须跳过tuple。无论如何,您所能做的最好的就是%s格式。否则,请编写自己的自定义文件编写器。savetxt不是什么特别或强大的东西。

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

我收到了同样的错误消息,看起来问题出在具有不同长度的数组上。所以您需要确保np.savetxt数组的长度相等。

如果没有一些示例数据,复制这个有点困难,但下面是我想到的。

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')

正如@Artier指出的,在Write object array to .txt file 中接受的答案的末尾有一个小片段,它指出您可以将数组保存为带fmt='%s'的字符串。使用这种格式似乎解决了我的问题(同样,如果没有数据样本,我无法完全重新创建您的问题)。

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

我要指出的是,如果您希望保存不同的数组,并希望使用单个位置来保存它们^{}是非常有用的。

相关问题 更多 >