简体   繁体   中英

Numpy reshape array of arrays to 1D

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?

创建数组时,请使用+连接列表,而不要将其包装在另一个列表中:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM