How can I save file by using savetxt in the python?

Question:

I have lists of data such as

a = [1,2,3,4,5]
b = [6,7,8,9,0]
c = [0,0,0,0,0]

I want to save this data into a file in a form of

1 6 0

2 7 0

3 8 0

4 9 0

5 0 0

I can do this by using "open". But I want to go with savetxt.

How can I save the data into the above form by using savetxt?

Asked By: Yeongkyu Lee

||

Answers:

import numpy as np


a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 0])
c = np.array([0, 0, 0, 0, 0])

all_data = np.vstack([a, b, c])

np.savetxt("data.txt", all_data.T, fmt="%d")

all_data stack the arrays rows by rows, so to print the data the way you want it you need to print the transpose, so all_data.T

You also need to format the output, so %d

Answered By: gee3107

A.T

import numpy as np

a = [1,2,3,4,5]
b = [6,7,8,9,0]
c = [0,0,0,0,0]

A = np.array([a,b,c])
B = A.T
np.savetxt("./demo1",B,fmt="%d")

we can use numpy let a,b,c become a
3×3 matrix
and use the transpose way of numpy
A:

[[1 2 3 4 5]  
 [6 7 8 9 0]  
 [0 0 0 0 0]]       

A.T

[[1 6 0]  
 [2 7 0]  
 [3 8 0]  
 [4 9 0]  
 [5 0 0]]  

then we can use

np.savetxt("./demo1",B,fmt="%d")

"./demo1": file name
B: data
fmt="%d": format

Answered By: mike john
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.