如何组合numpy数组和文本列并导出到csv

时间:2014-05-15 20:27:31

标签: python numpy

我想组合一个numpy数组和一个列,我将一个字符串作为标识符导出到csv文件,然后我可以将其导入到excel中。

例如:

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

所以现在我想将b附加到

的最后一列

一旦完成,我想使用np.savetxt(或类似的)将数组写入文件。

任何帮助非常感谢。

1 个答案:

答案 0 :(得分:6)

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')

写出类似

的内容
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

/tmp/out


根据Paul的建议,如果你有pandas,你可以很容易地形成一个DataFrame,然后调用它的to_csv方法:

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')