1

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).

3
  • 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. Commented Nov 30, 2016 at 15:57
  • 1
    Look at from numpy.lib import recfunctions. stackoverflow.com/a/27952861/901925 Commented Nov 30, 2016 at 16:02
  • @hpaulj thanks, I solved by combining recfunctions.append_fields and recfunctions.drop_fields, although I cannot specify an insert position. If no other solution comes up, and you would like to turn your comment to answer, I would be happy to accept it. Commented Nov 30, 2016 at 16:32

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.