我必须在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,%s,%f'
with open(filename, append_write) as f:
np.savetxt(f, results, delimiter=",", fmt=fmt)
N。B.你似乎想按行追加数据,在这种情况下,你需要重新整形才能将数据分成列(一行(。fmt
字符串应与要指定的列数相匹配。