本文介绍了savetxt在python,numpy中有两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据作为numpy 2D数组列表-

I have some data as numpy 2D array list-

array([[ 0.62367947],
       [ 0.95427859],
       [ 0.97984112],
       [ 0.7025228 ],
       [ 0.86436385],
       [ 0.71010739],
       [ 0.98748138],
       [ 0.75198057]])

array([[-1.,  1., -1.],
       [-1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1., -1.,  1.],
       [-1., -1., -1.],
       [ 1.,  1., -1.],
       [ 1., -1., -1.],
       [-1., -1.,  1.]])

我想将它们保存在txt文件中,以使它们看起来像

And I want to save them in a txt file so that they look like

0.62367947    -1 1 -1
0.95427859    -1 1 1
0.97984112     1 1 1

有人可以帮助我如何使用numpy savetxt吗

Can someone help me how I can do it using numpy savetxt

推荐答案

import numpy as np
R = np.array([[0.62367947],
              [0.95427859],
              [0.97984112],
              [0.7025228],
              [0.86436385],
              [0.71010739],
              [0.98748138],
              [0.75198057]])

phase = np.array([[-1., 1., -1.],
                  [-1., 1., 1.],
                  [1., 1., 1.],
                  [1., -1., 1.],
                  [-1., -1., -1.],
                  [1., 1., -1.],
                  [1., -1., -1.],
                  [-1., -1., 1.]])

np.savetxt('R2.txt', np.hstack([R, phase]), fmt=['%0.8f','%g','%g','%g'])

收益

0.62367947 -1 1 -1
0.95427859 -1 1 1
0.97984112 1 1 1
0.70252280 1 -1 1
0.86436385 -1 -1 -1
0.71010739 1 1 -1
0.98748138 1 -1 -1
0.75198057 -1 -1 1


np.hstack 水平堆叠数组.由于Rphase都是二维的,所以np.hstack([R, phase])会产生


np.hstack stacks arrays horizontally. Since R and phase are both 2-dimensional, np.hstack([R, phase]) yields

In [137]: np.hstack([R,phase])
Out[137]:
array([[ 0.62367947, -1.        ,  1.        , -1.        ],
       [ 0.95427859, -1.        ,  1.        ,  1.        ],
       [ 0.97984112,  1.        ,  1.        ,  1.        ],
       [ 0.7025228 ,  1.        , -1.        ,  1.        ],
       [ 0.86436385, -1.        , -1.        , -1.        ],
       [ 0.71010739,  1.        ,  1.        , -1.        ],
       [ 0.98748138,  1.        , -1.        , -1.        ],
       [ 0.75198057, -1.        , -1.        ,  1.        ]])

将此2D数组传递给np.savetxt会给您所需的结果.

Passing this 2D array to np.savetxt gives you the desired result.

这篇关于savetxt在python,numpy中有两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 10:09