Search code examples
pythonnumpygenfromtxt

Is it possible to add a new field in a numpy.genfromtxt output?


I loaded a csv file and used the header to specify the names of each column.

# Load the Data
data = np.genfromtxt('dat_h.csv',
                     delimiter=',',
                     names=True)

This is great, because I can access the columns by their name. For example...

DATES = data['Dates']
Temperature = data['Temp']

Say I have a vector of pressure observations that matches these measurements. Can I append the data structure with a new field that includes my pressure variable?

I want to do something like this ...

data.append('Pressure',pressure_vector)
# and then be able to access that field like I do the other fields
data['Pressure']

Solution

  • Look into this answer. Here are the docs for recfunctions.

    Mainly I think what you need is this:

    from numpy.lib.recfunctions import append_fields
    
    append_fields(data, 'Pressure', pressure_vector, np.double)