如何解决将 dtype=object numpy 数组保存在包含浮点数和字符串的 csv 文件中
我必须在 CSV 文件的每一行中保存 3 个字符串和一个浮点数。这是我所做的:
filename = "results.txt"
if os.path.exists(filename):
append_write = "a"
else:
append_write = "w"
#I am saving 3 strings and one float,they come from a numpy array
results = np.array(["a","b","c",0.32],dtype=object)
f = open(filename,append_write)
np.savetxt(f,results,delimiter=",")
f.close()
然而,这是我每次运行这样的代码时得到的错误
raise TypeError("Mismatch between array dtype ('%s') and "
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')
如何将 NumPy 数组中的此类混合变量保存到 CSV 文件中?
解决方法
您想为 np.savetxt
指定一个 fmt
字符串,如下所示:
results = np.array(["a","b","c",0.32],dtype=object).reshape(1,-1)
fmt = '%s,%s,%f'
with open(filename,append_write) as f:
np.savetxt(f,results,delimiter=",",fmt=fmt)
注意似乎您想逐行附加数据,在这种情况下,您需要重塑以将数据放入列(成一行)。 fmt
字符串应与您要指定的列数匹配。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。