简体   繁体   English

如何将列添加到ndarray?

[英]How do I add Columns to an ndarray?

So I have the below code that reads a file and gives me an ndarray using genfromtxt: 所以我有下面的代码读取文件,并使用genfromtxt给我一个ndarray:

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

Now, I wished to add another column to arr called "Marks". 现在,我希望在arr中添加另一个名为“Marks”的专栏。 Could you please help me out as to how I can do this? 你能帮我解决一下我怎么做的吗?

np.genfromtxt generates record array's. np.genfromtxt生成记录数组。 Columns cannot be concatenated to record array's in the usual numpy way. 列不能以通常的numpy方式连接到记录数组。 Use numpy.lib.recfunctions.append_fields : 使用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)

This returns: 返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM