如何使用numpy保存和读回多维字符串数组(可能)?

2024-09-29 01:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将数据保存到一个文件中,其中每行都遵循以下格式:<string1> <array of thousands of floats> <string2>。所以我考虑将数据连接成一个巨大的字符串数组,如下所示:

labels = ['label1', 'label2', 'label3']
values = [[0.1, 0.4, 0.5],
          [0.1, 0.2, 0.1],
          [0.5, 0.6, 1.0]]
descriptions = ['desc1', 'desc2', 'desc3']
concat1 = np.r_['1,2,0', labels, values]
concat2 = np.r_['1,2,0', concat1, descriptions]

结果:

[['label1' '0.1' '0.4' '0.5' 'desc1']
 ['label2' '0.1' '0.2' '0.1' 'desc2']
 ['label3' '0.5' '0.6' '1.0' 'desc3']]

我知道,如果每个子阵列足够小,我可以这样做:

np.savetxt('output.txt', concat2, fmt = "%s %s %s %s %s")

但我的问题涉及数千个值,所以一次键入一个变量的格式是不切实际的。你知道吗

关于如何将其保存到文件中还有其他建议吗?你知道吗

PS:把浮点数保存为字符串听起来有点奇怪,但我的上级这样问,所以。。。你知道吗


Tags: 文件of数据字符串labels格式npvalues
1条回答
网友
1楼 · 发布于 2024-09-29 01:30:01

没有numpy的解决方案:

labels = ['label1', 'label2', 'label3']
values = [[0.1, 0.4, 0.5],
          [0.1, 0.2, 0.1],
          [0.5, 0.6, 1.0]]
descriptions = ['desc1', 'desc2', 'desc3']

with open('output.txt', 'w') as handle:
    for label, nums, description in zip(labels, values, descriptions):
        handle.write('{} {} {}\n'.format(
            label,
            ' '.join(map(str, nums)),
            description,
        ))

output.txt的内容:

label1 0.1 0.4 0.5 desc1
label2 0.1 0.2 0.1 desc2
label3 0.5 0.6 1.0 desc3

或者从concat2开始:

with open('output.txt', 'w') as handle:
    for row in concat2:
        handle.write(' '.join(row))
        handle.write('\n')

相关问题 更多 >