pythonarraysnumpynumpy-dtype

Inserting columns in ndarray created using numpy.genfromtxt


I created a ndarray from a txt file using numpy.genfromtxt. The txt file looks like:

2505000
10.316     1.936     0.025    0   15   0   0
10.316     1.937     0.028    0   15   0   0
10.316     1.943     0.028    0   15   0   0
10.316     1.954     0.022    0    9  58   0
10.316     1.955     0.026    0    9  58   0

I am running the reading the data with:

data = np.genfromtxt(fname,
                     skip_header =1,
                     dtype = [('X','f'),('Y','f'),('Z','f'),('V', 'i'),('T', 'i')],
                     usecols = (0,1,2,4,5))

I am now trying to duplicate the 4th column (the one I called V) and place it just after itself (before the last T column).

I know I can copy the column by doing data['V'], but how do I place this copy in between V and T (the 4th and 5th columns)? I had a look at numpy.insert, but I am not sure how to specify the index (the obj argument). I tried with numpy.insert(data_copy, data_copy['T'],data_copy['V']) with no luck (I received IndexError: index 61 is out of bounds for size 20).


Solution

  • You have to make a new dtype with the added field, and copy values by field name from the original array to the new one.

    recfunctions has functions to do this (and related actions):

     from numpy.lib import recfunctions
    

    numpy dtype error - (structured array creation)