问题描述
我有以下数组:
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 时:
When I try to save the data as 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')
这是为什么呢?我该如何解决这个问题?
Why is that? How can I solve the issue?
谢谢.
推荐答案
如果没有一些示例数据,复制这个有点困难,但这是我想出的.
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')
正如@Artier 所指出的,在 将对象数组写入 .txt 文件 指出您可以使用 fmt='%s'
将数组保存为字符串.使用这种格式似乎可以解决我的问题(同样,如果没有数据样本,我无法完全重现您的问题).
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')
我会指出,如果您要保存不同的数组并希望在一个位置保存它们 savez
非常有用.
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.
这篇关于TypeError: 数组 dtype ('object') 和格式说明符 ('%.18e') 不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!