如何合并一个numpy数组和一个文本列并导出到csv [英] How to combine a numpy array and a text column and export to csv

查看:63
本文介绍了如何合并一个numpy数组和一个文本列并导出到csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

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

所以现在我想将b附加到a的最后一列

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

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

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

写类似

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 方法:

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

这篇关于如何合并一个numpy数组和一个文本列并导出到csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆