2

I have a file with the content of

18
21
24
27
30

And the array of

[[ 1  6 11]
 [ 2  7 12]
 [ 3  8 13]
 [ 4  9 14]
 [ 5 10 15]]

How can I write this array to file so that each row will be corresponding with the appropriate lines such as it becomes something like this:

18    1  6 11
21    2  7 12
24    3  8 13
27    4  9 14
30    5 10 15

I have used this code, but it does not write the code as I want. The code:

import numpy as np

    ourlist = []
    for i in range(1, 16):
        ourlist.append(i)


    mydata = np.matrix([ourlist])
    array_from_list=(mydata.reshape(3, 5))
    x_transpose = (np.transpose(array_from_list))   # the array above

    with open('5rows.txt','a') as f:                #the file containing numbers
     for elements in x_transpose:
         f.write(str(elements))
         f.write('\n')

It instead writes elements to the end of line. If possible, could you tell me how I can do this, please ? I really appreciate your help !

2
  • Have you tried using a dataframe? It might make things easier for you. Commented Jun 12, 2017 at 2:36
  • So the first column in the file is the sum of the row. Is this not put there by you? My answer assumes a horizontal append is required, but maybe you are first writing the sums, then trying to write the matrix next to it. That would not be a good way to go about that. Maybe I'm being presumptuous, but I thought I should be curious for your future benefit. Commented Jun 12, 2017 at 2:47

3 Answers 3

2

This code bellow might solve your problem, although it is not very performatic. You may be able to improve the solution to better fit your needs.

import numpy as np

ourlist = []

for i in range(1, 16):
    ourlist.append(i)


mydata = np.matrix([ourlist])
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list))

with open('file.txt', 'r') as f:
    lines = f.readlines()

with open('file.txt', 'w') as f:
    i = 0
    for line in lines:
        f.write(str(int(line)) + "  " + str(x_transpose[i])[1:-1][1:-1] + "\n")
        i+=1
Sign up to request clarification or add additional context in comments.

Comments

2

np.savetxt writes a csv file. In this case the trick is to assemble your two arrays/lists into a composite array, and then format it as you want:

In [100]: mydata = np.arange(1,16).reshape(3,5)
In [101]: mydata
Out[101]: 
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])
In [102]: mydata = np.arange(1,16).reshape(3,5).T
In [103]: mydata
Out[103]: 
array([[ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14],
       [ 5, 10, 15]])
In [104]: elements = np.arange(18,31,3)
In [105]: elements
Out[105]: array([18, 21, 24, 27, 30])
In [106]: arr = np.column_stack((elements, mydata))
In [107]: arr
Out[107]: 
array([[18,  1,  6, 11],
       [21,  2,  7, 12],
       [24,  3,  8, 13],
       [27,  4,  9, 14],
       [30,  5, 10, 15]])
In [108]: np.savetxt('test.txt',arr, fmt='%2d   %3d %3d %3d')
In [109]: cat test.txt
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

Equivalently I could zip to two arrays; combine row values into one tuple, and format that:

In [112]: for e, d in zip(elements, mydata):
     ...:     ed = (e,)+tuple(d)
     ...:     print('%2d   %3d %3d %3d'%ed)
              # print(('%d  '%e) + ' '.join(['%3d']*3)%tuple(d))
     ...:     
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

I'm using print but you could switch that to file write.

Comments

1

I think you are misunderstanding what 'append' means. When you are appending data to a file, that means vertical append: adding content to the end of the file. If you want to do a horizontal append you first will have to read the data in and then write everything back.

import numpy as np

mydata = np.matrix(list(range(1, 16)))
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list))   # the array above

with open('5rows.txt','r') as f:
    lines = list(f)
with open('5rows.txt','w') as f:
    for existing, new in zip(lines[:16], x_transpose):
        f.write('{}\t{}\n'.format(existing, '\t'.join(new)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.