0

How do I get x to become a 1D array? I found it convenient to create x like this,

x=np.array([[0,-1,0]*12,[-1,0,0]*4])
print x
print len(x)

returns

array([ [0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0],
       [-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0]], dtype=object)

2

I also tried making it like this, but the length is still 2

y=((0,1,0)*12,(-1,0,0)*4)
print y

returns

((0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0), (-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0))

I have tried using numpy.reshape (on both x and y):

np.reshape(x,48)

but I get this error:

ValueError: total size of new array must be unchanged

Is it possible to reshape x or y when I have declared them like I did?

2
  • Your x is 2 lists of different length, 36 and 12. Do you want one of length 48? Commented Jun 20, 2015 at 14:25
  • yes, actually the first answer does this nicely Commented Jun 20, 2015 at 22:45

2 Answers 2

2

When you create the array, concatenate the lists with + instead of packing them in another list:

x = np.array([0,-1,0]*12 + [-1,0,0]*4)
Sign up to request clarification or add additional context in comments.

Comments

0

I think you are looking to make a 1D numpy array that has a length of 48. Try,

    import numpy as np
    x=np.array([[0,-1,0]*12])
    x= np.append(x,[-1,0,0]*4)
    print (x)
    print (len(x))

This yields,

[ 0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0
 -1  0  0 -1  0  0 -1  0  0 -1  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0]
48

1 Comment

Thanks. I actually have a longer array that has more of those groups of 12 so I wanted to create it in a single line like with the + method above.

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.