简体   繁体   中英

Save two arrays with Numpy.savetxt into a .csv file, with a column for each array

I have difficulties with numpy.savetxt . Particularly, I have two arrays with B created by the following command np.arrrange(2000,5000) , while print(A) is like [0 2 1 ... 0 1 2] and I would like to save both of them in a single csv file with the format array B in the first column and array A in the second column:

2000 0

2001 2

2002 1

I tried with the command np.savetxt('output.csv', np.c_[B,A], delimeter=',') but what I get is that both B and A are in the same column:

2000+0

2001+2

2002+1

May you be so kind to tell me my mistake and a possible solution?

Edit I managed to get a solution thanks to FHTMitchell, the only thing that is not working now is that I don't get the 0: My output is the following

`2000

2001,2

2002,1`

I tried with

res = np.c_[B,A] output = res.astype(int) np.savetxt('out.csv', output, fmt='%d', delimiter=',')

But I still don't get the zeros.

Your solution worked fine for me, although I needed to set the fmt specifier to '%d' for integers. What version of numpy are you on (for me np.__version__ == '1.14.1' )?

Anyway, here is a possible solution with more standard numpy:

import numpy as np

A = np.array([0, 2, 1])
B = np.arange(2000, 2003)

np.savetxt('out.csv', np.column_stack((B, A)), fmt='%d', delimiter=',')

Outputs

2000,0
2001,2
2002,1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM