gpt4 book ai didi

python - 格式化 numpy 数组并保存到 *.txt

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:16 26 4
gpt4 key购买 nike

我想格式化一个 numpy 数组并将其保存在 *.txt 文件中

numpy 数组如下所示:

a = [ 0.1   0.2   0.3   0.4   ... ] , [ 1.1   1.2   1.3   1.4   ... ] , ...

输出 *.txt 应如下所示:

0   1:0.1   2:0.2   3:0.3   4:0.4   ...
0 1:1.1 2:1.2 3:1.3 1:1.4 ...
...

不知道该怎么做。

谢谢。

好的,谢谢。我稍微修正了你的答案

import numpy as np

a = np.array([[1,3,5,6], [4,2,4,6], [6,3,2,6]])

ret = ""

for i in range(a.shape[0]):
ret += "0 "
for j in range(a.shape[1]):
ret += " %s:%s" % (j+1,float(a[i,j])) #have a space between the numbers for better reading and i think it should starts with 1 not with 0 ?!
ret +="\n"

fd = open("output.sparse", "w")
fd.write(ret)
fd.close()

你觉得可以吗?!

最佳答案

相当简单:

import numpy as np

a = np.array([[0.1, 0.2, 0.3, 0.4], [1.1, 1.2, 1.3, 1.4], [2.1, 2.2, 2.3, 2.4]])

with open("array.txt", 'w') as h:
for row in a:
h.write("0")
for n, col in enumerate(row):
h.write("\t{0}:{1}".format(n+1, col)) # you can change the \t (tab) character to a number of spaces, if that's what you require
h.write("\n")

输出:

0       1:0.1   2:0.2   3:0.3   4:0.4
0 1:1.1 2:1.2 3:1.3 4:1.4
0 1:2.1 2:2.2 3:2.3 4:2.4

我的原始示例涉及大量磁盘写入。如果您的阵列很大,这可能会非常低效。但是,可以减少写入次数,例如:

with open("array.txt", 'w') as h:  
for row in a:
row_str = "0"
for n, col in enumerate(row):
row_str = "\t".join([row_str, "{0}:{1}".format(n+1, col)])
h.write(''.join([row_str, '\n']))

您可以通过构建一个大字符串并将其写入末尾来将写入次数进一步减少到仅一次,但是在这真正有益的情况下(即一个巨大的数组),您随后会遇到内存问题从构建一个巨大的字符串。无论如何,这取决于你。

关于python - 格式化 numpy 数组并保存到 *.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17740749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com