2

I want to save the numpy array as a csv file in python

For example given the following array

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

I would like to have a csv file like :

 1   4    7
 2   5    8
 3   6    9

My code bellow gives me the result like :

a.tofile('file1.csv',sep=',')

result:  1 2 3 4 5 6 7 8 9 

I have tried the following code as well

df = pd.DataFrame(a)

df.to_csv("file2.csv", index=None)

which does not give me the desired result again

1    
2    
3    
4    
5
6
7
8
9

I would appreciate your comments and suggestion.

2 Answers 2

3

You could do pd.DataFrame(a).T.to_csv('file2.csv', index=False, header=None)

In [1210]: print pd.DataFrame(a).T.to_csv(index=False, header=None)
1,4,7
2,5,8
3,6,9

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

Simply with numpy.ndarray.transpose() and numpy.savetxt() routines:

a = np.array([[1,2,3], [4,5,6], [7,8,9]])
np.savetxt('output.csv', a.transpose(), delimiter=',', fmt='%d')

output.csv contents:

1,4,7
2,5,8
3,6,9

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.