1

I am trying to save the results from a loop in a np.array.

    import numpy as np
    p=np.array([])
    points= np.array([[3,0,0],[-1,0,0]])

    for i in points:
       for j in points:
          if j[0]!=0:
             n=i+j
       p= np.append(p,n)

However the resulting array is a 1D array of 6 members.

    [2.  0.  0. -2.  0.  0.]

Instead I am looking for, but have been unable to produce:

    [[2,0,0],[-2,0,0]]

Is there any way to get the result above?

Thank you.

1
  • What exactly are you trying to do? There may be a better way to accomplish it. Otherwise try p.reshape(points.shape) Commented Sep 17, 2014 at 7:46

2 Answers 2

2

One possibility is to turn p into a list, and convert it into a NumPy array right at the end:

p = []
for i in points:
   ...
   p.append(n)
p = np.array(p)
Sign up to request clarification or add additional context in comments.

Comments

0

What you're looking for is vertically stacking your results:

import numpy as np
p=np.empty((0,3))
points= np.array([[3,0,0],[-1,0,0]])

for i in points:
  for j in points:
    if j[0]!=0:
      n=i+j
  p= np.vstack((p,n))
print p

which gives:

[[ 2.  0.  0.]
 [-2.  0.  0.]]

Although you could also reshape your result afterwards:

import numpy as np
p=np.array([])
points= np.array([[3,0,0],[-1,0,0]])

for i in points:
  for j in points:
    if j[0]!=0:
      n=i+j
  p= np.append(p,n)
p=np.reshape(p,(-1,3))
print p

Which gives the same result .

I must warn you, hovever, that your code fails if j[0]!=0 as that would make n undefined...

np.vstack np.empty np.reshape

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.