How do I add Columns to an ndarray?

匆匆过客 提交于 2019-12-11 04:02:48

问题


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)

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


回答1:


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)

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


来源:https://stackoverflow.com/questions/14847710/how-do-i-add-columns-to-an-ndarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!