numpy savetxt:如何将整数和浮点numpy数组保存到文件的保存行中



我有一组整数和一组numpy数组,我想用np.savetxt将相应的整数和数组存储在同一行中,行之间用\n分隔。

在txt文件中,每一行应该如下所示:

12345678 0.282101 -0.343122 -0.19537 2.001613 1.034215 0.774909 0.369273 0.219483 1.526713 -1.637871 

浮点数应以空格分隔

我尝试使用以下代码来解决这个

np.savetxt("a.txt", np.column_stack([ids, a]), newline="n", delimiter=' ',fmt='%d %.06f')

但不知何故,我无法找到整数和浮点的正确格式。

有什么建议吗?

请指定;整数集";以及";numpy数组集合";是:从您的示例来看,ids是一个列表或1d numpy数组,a是一个2d numpy数组。

如果你试图将一个整数列表与一个2d数组组合在一起,你可能应该避免np.savetxt,并首先转换为字符串:

import numpy as np
ids = [1, 2, 3, 4, 5]
a = np.random.rand(5, 5)
with open("filename.txt", "w") as f:
for each_id, row in zip(ids, a):
line = "%d " %each_id + " ".join(format(x, "0.8f") for x in row) + "n"
f.write(line)

在filename.txt中给出输出:

1 0.38325380 0.80964789 0.83787527 0.83794886 0.93933360
2 0.44639702 0.91376799 0.34716179 0.60456704 0.27420285
3 0.59384528 0.12295988 0.28452126 0.23849965 0.08395266
4 0.05507753 0.26166780 0.83171085 0.17840250 0.66409724
5 0.11363045 0.40060894 0.90749637 0.17903019 0.15035594

最新更新