Вопрос

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.

Это было полезно?

Решение

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')
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top