Skip to content Skip to sidebar Skip to footer

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: arr = np.genfromtxt(filename, delimiter=',', converters={'Date': make_date},

Solution 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.libimport recfunctions as rfn
fromStringIO importStringIO

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

Post a Comment for "How Do I Add Columns To An Ndarray?"