1

I have a 2D numpy array visrec. If I do

print visrec[0,:]

I am getting this output:

[  a1   a2   a3   a4  a5   a6]

where a1, a2,.. are dtype=float64

More clearly, visrec is a 1x6 matrix stored in a numpy.array object. It is initially created with this command:

visrec=numpy.array(numpy.zeros((1,6)))

In a loop, I am modifiying visrec and storing the modification record in a list. I am basicly appending each modification to the list rec_history=[]. I use this command:

rec_history.append(visrec[0,:])

Then, In order to test it, I just want to print the first element of rec_history with this command:

print rec_history[0]

The output is in the following format:

[ a1   a2  a3   a4   a5   a6]

Up to here everything is as I expected. But, if I try to print more than one element of rec_history, I get an unexpected output. I issue this command:

print rec_history[0:3] 

and get the following output:

[array([ a1,  a2,  a3,  a4,  a5 ,
        a6]), array([  b1,   b2,   b3,
         b4,   b5,   b6]), array([  c1,   c2,   c3,
         c4,   c5,   c6])]

Is this normal? Am I actually storing the array objects in my record list. If this is the case why am I not getting a different kind of output if I only print one element of the list? Is this related with the function print? I do not want to store the array objects, I want to store the lists of numbers in a record list. How can I do this? I know matlab but, I guess it is not helping me here.

2
  • It's pretty normal. Please point out what kind of output you want to see when you print rec_history. Commented May 12, 2012 at 23:16
  • Code should be indented by four spaces, > is for quotes. Commented May 13, 2012 at 0:08

1 Answer 1

1

You are storing slices of your original array, and since you got several arrays from your slice of rec_history[0:3], I would assume you have appended to it at least 3 times.

If you want the first three items of the first item of rec_history you would need to do:

rec_history[0][:3]

If you for some reason don't want the arrays inside rec_history you could change the append line to:

rec_history.append(list(visrec[0,:]))

This would be good if you plan to change visrec and want to see how it looked in previous states, as just appending array-slices as you have done will only create references to that part of the array. Hence, if you change in the array with your code, it will change the stuff in rec_history too.

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

1 Comment

I believe in numpy that references to a portion of the array are called a view (for anyone interested in googling it)

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.