Numpy reshape array of arrays to 1D

922 views Asked by At

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

There are 2 answers

0
user2357112 On BEST ANSWER

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)
1
nitin On

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