numpy savetxt mismatch between array dtype ('object') and format specifier (' .18e')

numpy.savetxt 是一个用于将数组保存到文本文件中的函数。当出现 "mismatch between array dtype ('object') and format specifier (' .18e')" 的错误时,通常是因为数组中存在非数值元素导致无法使用浮点数格式说明符 ' .18e' 来格式化。

解决方法是检查数组中是否有非数值元素,并在保存之前将其转换为字符串或数值。例如:

import numpy as np
a = np.array([1, 2, "string"])
# convert non-numeric elements to string
a = np.array(a, dtype=np.str)
np.savetxt("file.txt", a, fmt="%s")

如果你确定数组中不存在非数值元素,但是仍然出现此错误,则可能是数组的 dtype 不是 np.float 或 np.double,需要通过使用 np.array(a, dtype=np.float)或np.array(a, dtype=np.double)转换。

  •