如何将3D数组写入文本文件

时间:2018-08-31 18:21:37

标签: python numpy

我有这样的数组:

[[-3.75536609e+00  9.41899478e-01  1.59805989e+00 -8.97728577e-02
  -3.67324662e+00  2.85971731e-01]
 [-1.48593640e+00  6.56555116e-01  6.41966641e-01 -2.62360811e-01
  -4.66498184e+00 -8.62938017e-02]
 [ 7.05197873e-03 -4.12116805e-03 -1.30933505e-02  5.76611329e-03
  -6.51661423e-04 -9.73143987e-03]
 ...
 [ 7.28487849e-01 -2.02445209e-01 -1.56245055e-02 -1.48709917e+00
  -4.94436502e+00 -1.88474905e+00]
 [ 6.85976565e-01 -1.20424531e-01 -2.20480785e-01 -1.23380101e+00
  -3.60452390e+00 -1.54651344e+00]
 [ 1.47314686e-02  1.42228836e-02 -1.20135369e-02 -4.32784623e-03
  -8.07471294e-03  2.29109559e-04]]
[-0.6025902  -0.31237862 -1.2150506   3.072987   -1.3560013  -1.0883616 ]

我希望能够将此数组写入文本文件。每个元素应逐行打印。例如,第一个可能看起来像这样

-3.75536609e+00 
 9.41899478e-01 
 1.59805989e+00 
-8.97728577e-02
 -3.67324662e+00 
 2.85971731e-01

我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果这些是numpy数组,则可以将np.savetxtdelimiter='\n'一起使用,并枚举数组:

给出数组x

>>> x
array([[-3.75536609e+00,  9.41899478e-01,  1.59805989e+00,
        -8.97728577e-02, -3.67324662e+00,  2.85971731e-01],
       [-1.48593640e+00,  6.56555116e-01,  6.41966641e-01,
        -2.62360811e-01, -4.66498184e+00, -8.62938017e-02],
       [ 7.05197873e-03, -4.12116805e-03, -1.30933505e-02,
         5.76611329e-03, -6.51661423e-04, -9.73143987e-03]])

使用:

[np.savetxt(f'array{n}.txt',i,delimiter='\n') for n,i in enumerate(x)]

您将获得3个文本文件:

array0.txt将是:

-3.755366089999999879e+00
9.418994779999999567e-01
1.598059890000000038e+00
-8.977285769999999998e-02
-3.673246620000000018e+00
2.859717310000000068e-01

等...

[EDIT] 似乎我误解了您的问题。如果只需要一个txt文件,请使用:

np.savetxt('array.txt', x.flatten(), delimiter='\n')

哪个会给array.txt

-3.755366089999999879e+00
9.418994779999999567e-01
1.598059890000000038e+00
-8.977285769999999998e-02
-3.673246620000000018e+00
2.859717310000000068e-01
-1.485936399999999935e+00
6.565551160000000497e-01
6.419666410000000045e-01
-2.623608110000000271e-01
-4.664981840000000268e+00
-8.629380170000000572e-02
7.051978730000000098e-03
-4.121168050000000374e-03
-1.309335049999999986e-02
5.766113290000000370e-03
-6.516614230000000382e-04
-9.731439870000000575e-03

答案 1 :(得分:0)

来自this solution

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

创建一个简单的列表。然后将其转储到文件:

with open(outfile) as f:
    f.write("\n".join(flatlist))