简体   繁体   中英

Reshape 1-D Numpy Array to 2-D

I have a 1-D numpy array of 38 (x,y) coordinates created by (doc here ):

npArray = arcpy.da.FeatureClassToNumPyArray(fc,["SHAPE@XY"])

This outputs a (38,) array, like:

[([X1, Y1],)
 ([X2, Y2],)
 ...
 ([X38, Y38],)]

edit: Here are the first 5 lines of actual output, and the dtype:

[([614276.776070848, 6086493.437772478],)
 ([626803.3576861953, 6101090.488548568],)
 ([627337.6049131282, 6100051.791447324],)
 ([627340.8526022129, 6099601.263191574],)
 ([629011.3422856168, 6099079.306533674],)

dtype([('SHAPE@XY', '<f8', (2,))])

but I want a (38,2) array like:

[(X1, Y1)
 (X2, Y2)
 ...
 (X38, Y38)]

How do I make this happen?

I've tried

numpy.reshape(npArray, (-1,2)) 

but this reshuffles the coordinate pairs to a (19,2) array.

The doc http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000015000000 says it returns a structured array.

Since the dtype is:

dtype([('SHAPE@XY', '<f8', (2,))

you can access this field by name

npArray['SHAPE@XY']

the result should be a (38,2) array. It will be a view on the original.


Creating a structured array like this from scratch is a bit tricky, since numpy tries to create the highest dimensional array it can. The surest way is to create an empty array of the desired size and dtype, and then assign values field by field.

In [56]: X=np.zeros((5,),dtype=([('f0',int,(2,))]))
In [57]: X
Out[57]: 
array([([0, 0],), ([0, 0],), ([0, 0],), ([0, 0],), ([0, 0],)], 
      dtype=[('f0', '<i4', (2,))])
In [58]: X['f0']=np.arange(10).reshape(5,2)
In [59]: X
Out[59]: 
array([([0, 1],), ([2, 3],), ([4, 5],), ([6, 7],), ([8, 9],)], 
      dtype=[('f0', '<i4', (2,))])
In [60]: X['f0']
Out[60]: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

Does numpy.squeeze(numpy.array(npArray)) work? If not, can you post an array with numbers?

EDIT: I've not used arcpy (may be worth tagging this in the question) but from the docs here: http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000015000000

It looks like you need to use npArray["SHAPE@XY"] to access the numpy array. The array should then already be the required shape.

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