如何将列添加到ndarray? [英] How do I add Columns to an ndarray?

查看:79
本文介绍了如何将列添加到ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码,该代码读取文件并使用genfromtxt给我一个ndarray:

So I have the below code that reads a file and gives me an ndarray using genfromtxt:

arr = np.genfromtxt(filename, delimiter=',', converters={'Date': make_date},
                    names=('Date', 'Name','Age'), dtype=None)

现在,我希望在arr中添加另一列称为标记".您能帮我解决我该怎么做吗?

Now, I wished to add another column to arr called "Marks". Could you please help me out as to how I can do this?

推荐答案

np.genfromtxt生成记录数组.列不能以通常的numpy方式连接到记录数组.使用numpy.lib.recfunctions.append_fields:

np.genfromtxt generates record array's. Columns cannot be concatenated to record array's in the usual numpy way. Use numpy.lib.recfunctions.append_fields:

import numpy as np
from numpy.lib import recfunctions as rfn
from StringIO import StringIO

s = StringIO('2012-12-10,Peter,30\n2010-01-13,Mary,31')
arr = np.genfromtxt(s, delimiter=',', names=('Date', 'Name','Age'), dtype=None)
new_arr = rfn.append_fields(arr, names='Marks', data=['A','C+'], usemask=False)

这将返回:

>>> arr
array([('2012-12-10', 'Peter', 30), ('2010-01-13', 'Mary', 31)], 
  dtype=[('Date', '|S10'), ('Name', '|S5'), ('Age', '<i8')])
>>> new_arr
array([('2012-12-10', 'Peter', 30, 'A'), ('2010-01-13', 'Mary', 31, 'C+')], 
  dtype=[('Date', '|S10'), ('Name', '|S5'), ('Age', '<i8'), ('Marks', '|S2')])

这篇关于如何将列添加到ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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