2017-06-17 6 views
1

各行がこの形式に従うファイルにデータを保存する必要があります:<string1> <array of thousands of floats> <string2>。だから私は以下のように、一つの巨大な文字列配列にデータを連結することについて考え:多次元文字列配列(おそらく)を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'] 
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") 

しかし、私の問題には何千もの値が含まれているため、一度に1つの変数を入力するのは実用的ではありません。

これをファイルに保存する方法の他の提案はありますか?

PS:それは奇妙なビット列としてフロートを保存するために聞こえるが、私の優れたnumpyなし

+1

[numpy.ndarray.tofile](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.tofile.html)を試しましたか? –

+2

'fmt ="%s "は動作するはずです。 'savetxt'は配列' row'の値の数を考慮に入れてその値を複製します。つまり、 'newfmt = delimiter.join([fmt] * len(row))'を構築します。 – hpaulj

+0

@BradSolomonそれは動作しますが、多次元配列に読み込むことはできません。これは1行で保存されます。 – plethora

答えて

1

ソリューションをこのようにそれを尋ね、そう...:output.txt

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, 
     )) 

内容:

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')