简体   繁体   English

将一维Numpy阵列重塑为二维

[英]Reshape 1-D Numpy Array to 2-D

I have a 1-D numpy array of 38 (x,y) coordinates created by (doc here ): 我有一个由(doc here )创建的38(x,y)坐标的一维numpy数组:

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

This outputs a (38,) array, like: 这将输出(38,)数组,例如:

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

edit: Here are the first 5 lines of actual output, and the dtype: 编辑:这是实际输出的前5行和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: 但我想要一个(38,2)数组,例如:

[(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. 但这会将坐标对改组为(19,2)数组。

The doc http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000015000000 says it returns a structured array. 文档http://resources.arcgis.com/zh-CN/help/main/10.1/index.html#//018w00000015000000说,它返回一个结构化数组。

Since the dtype is: 由于dtype为:

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

you can access this field by name 您可以按名称访问此field

npArray['SHAPE@XY']

the result should be a (38,2) array. 结果应该是(38,2)数组。 It will be a view on the original. 这将是一个view上的原始。


Creating a structured array like this from scratch is a bit tricky, since numpy tries to create the highest dimensional array it can. 从头开始创建像这样的结构化数组有些棘手,因为numpy尝试创建可以做到的最大维数数组。 The surest way is to create an empty array of the desired size and dtype, and then assign values field by field. 最可靠的方法是创建一个具有所需大小和dtype的空数组,然后逐字段分配值。

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? numpy.squeeze(numpy.array(npArray))是否有效? 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 编辑:我没有使用arcpy(可能值得在问题中对此进行标记),但是来自这里的文档: 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. 看来您需要使用npArray [“ SHAPE @ XY”]访问numpy数组。 The array should then already be the required shape. 然后,该阵列应该已经是所需的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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