3

I want to combine a numpy array and a column which i a string as an identifier for export to a csv file which i can then import into excel.

For example:

a=np.random.rand(6,4)
b=[]
for i in range(6):
  b.append('test')

So now i want to append b to the last column of a

Once that is done I want to use np.savetxt (or similar) to write the array to a file.

Any help much appreciated.

1
  • pandas might be good for this. Combine the columns into a pandas Dataframe. Dataframes have a write_csv() Commented May 15, 2014 at 21:05

1 Answer 1

7
import numpy as np

a = np.random.rand(6,4)
b = ['test']*6

c = np.column_stack([a,b])
np.savetxt('/tmp/out', c, delimiter=',', fmt='%s')

writes something like

0.70503807191,0.19298150889,0.962915679186,0.655430709887,test
0.586655200042,0.379720344068,0.136924270418,0.547277504174,test
0.777238053817,0.642467338742,0.709351872598,0.932239808362,test
0.386983024375,0.753005132745,0.124107902275,0.472997270033,test
0.169711196953,0.735713880779,0.280588048467,0.726851876957,test
0.20578446385,0.379406838045,0.640154333103,0.579077700263,test

to /tmp/out.


Following up on Paul's suggestion, if you have pandas, you could form a DataFrame quite easily and then call its to_csv method:

import numpy as np
import pandas as pd

a = np.random.rand(6,4)
b = np.asarray(['test']*6)

df = pd.DataFrame(a)
df['b'] = b

df.to_csv('/tmp/out')
Sign up to request clarification or add additional context in comments.

1 Comment

...and to combine multiple numpy arrays one solution is: np.savetxt(filename,np.vstack((npArray1,npArray2)).T,delimiter=',', fmt='%s')

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.