我不确定您尝试了什么,但您需要使用np.savetxt 中的header 参数。此外,您需要正确连接数组。最简单的方法是使用np.c_,它将您的一维数组强制转换为二维数组,然后按照您期望的方式将它们连接起来。
>>> time = np.array([0,60,120,180])
>>> operation1 = np.array([12,23,68,26])
>>> operation2 = np.array([100,123,203,301])
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2],
header='Filexy\ntime operation1 operation2', fmt='%d',
delimiter='\t')
example.txt 现在包含:
# Filexy
# time operation1 operation2
0 12 100
60 23 123
120 68 203
180 26 301
还要注意使用fmt='%d' 在输出中获取整数值。 savetxt 默认保存为浮点数,即使是整数数组。
关于分隔符,您只需要使用delimiter 参数即可。这里不清楚,但实际上列之间有选项卡。例如,vim 使用点向我显示标签:
# Filexy
# time operation1 operation2
0· 12· 100
60· 23· 123
120·68· 203
180·26· 301
附录:
如果你想添加标题并且在数组之前添加一个额外的行,你最好创建一个自定义标题,并用你自己的注释字符完成。使用comment 参数来防止savetxt 添加额外的#。
>>> extra_text = 'Answer to life, the universe and everything = 42'
>>> header = '# Filexy\n# time operation1 operation2\n' + extra_text
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2],
header=header, fmt='%d', delimiter='\t', comments='')
产生
# Filexy
# time operation1 operation2
Answer to life, the universe and everything = 42
0 12 100
60 23 123
120 68 203
180 26 301