我正在使用arcpy中的TableToNumpyArray。我正在导入的表"x"有99行和6列。
x
输出
print(x)
输出
np.shape(x)
(99,)
我想把它转换成没有列表的(99,6(。
根据评论和以前的答案,我尝试了:
y = np.stack(x)
np.shape(y)
(99,)
查看的文档
TableToNumPyArray
ArcGIS Pro 2.8 | Other versions
Summary
Converts a table to NumPy structured array.
您的x
Out[168]
显示不完整;它缺少最后的CCD_ 3行。如果您认为数组应该是(99,6(,那么dtype
必须有6个fields
。
再多的stack
、concatenate
或reshape
也不会将fields
转换为columns
。
https://numpy.org/doc/stable/user/basics.rec.html
下面是一个结构化的数据类型和数组示例:
In [23]: dt = np.dtype('f,f,f')
In [24]: dt
Out[24]: dtype([('f0', '<f4'), ('f1', '<f4'), ('f2', '<f4')])
In [25]: arr = np.ones(4, dtype=dt)
In [26]: arr
Out[26]:
array([(1., 1., 1.), (1., 1., 1.), (1., 1., 1.), (1., 1., 1.)],
dtype=[('f0', '<f4'), ('f1', '<f4'), ('f2', '<f4')])
请注意,显示内容看起来像元组列表。注意数据类型。
因为所有字段都是浮动的。创建二维数值数组的一个好方法是:
In [27]: arr.tolist()
Out[27]: [(1.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, 1.0)]
In [28]: np.array(arr.tolist())
Out[28]:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
CCD_ 11相对较快。
另一种方法是使用recfunctions
实用程序:
In [29]: import numpy.lib.recfunctions as rf
In [30]: rf.structured_to_unstructured(arr)
Out[30]:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=float32)
对于公共字段dtype,也可以使用view
,但它需要整形:
In [32]: arr.view(np.float32)
Out[32]: array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], dtype=float32)
In [33]: arr.view(np.float32).reshape(4,3)
Out[33]:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=float32)
这是一个棘手的问题,但我找到了多种解决方案。首先,注意数组中元素的类型是";对象";(编辑:你刚刚发布了你的类型,它是不同的,但我确实认为解决方案也应该适用于你。你得到的np.stack解决方案应该也适用,但你忘了重塑它(,因此你有一个1D对象数组,当你问它的形状时,你会得到(99,(
因此,让我们创建一个与您的数组类型相同的示例数组:
l=[(1,2),(3,4)]
a = np.empty(len(l), dtype=tuple)
a[:] = l
print(f"a's shape: {a.shape}")
其输出为:a's shape: (2,)
对此的经典解决方案是从中创建一个列表,然后重建numpy数组,通常如下所示:
print(np.array(list(a)).shape)
输出CCD_ 15
但你要求在没有清单的情况下这样做。另一种方法是使用";连接";像这样:
a = np.concatenate(a).reshape(len(a),*np.shape(a[0]))
这也会导致你想要什么。我们在这里所做的是将元组一个接一个地连接在一起,作为一个大数组,然后将其重塑为所需的长度。
编辑:同样适用于你提供的堆栈解决方案,你忘记了在之后重塑
a= np.stack(a).reshape(len(a),*np.shape(a[0]))