麻木数组将数组中的隐列表转换为维度

问题描述

我使用的是来自 arcpyTableToNumpyArray。我要导入的表“x”有 99 行和 6 列。

x

Output

print(x)

Output

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] 显示不完整;它缺少最后的 dtype 行。如果您认为数组应该是 (99,6),那么 dtype 必须有 6 个 fields

没有多少 stackconcatenatereshape 会将 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',('f2','<f4')])
In [25]: arr = np.ones(4,dtype=dt)
In [26]: arr
Out[26]: 
array([(1.,1.,1.),(1.,1.)],dtype=[('f0','<f4')])

注意显示的内容看起来像一个元组列表。并注意 dtype。

因为所有字段都是浮点数。创建二维数值数组的一种好方法是:

In [27]: arr.tolist()
Out[27]: [(1.0,1.0,1.0),(1.0,1.0)]
In [28]: np.array(arr.tolist())
Out[28]: 
array([[1.,1.],[1.,1.]])

tolist() 相对较快。

另一种方法是使用 recfunctions 实用程序:

In [29]: import numpy.lib.recfunctions as rf
In [30]: rf.structured_to_unstructured(arr)
Out[30]: 
array([[1.,1.]],dtype=float32)

对于通用字段 dtype,也可以使用 view,但需要重新整形:

In [32]: arr.view(np.float32)
Out[32]: array([1.,dtype=float32)
In [33]: arr.view(np.float32).reshape(4,3)
Out[33]: 
array([[1.,dtype=float32)
,

一个令人讨厌的问题,但我找到了多种解决方案。 首先,请注意数组中元素的类型是“对象”(编辑:您刚刚发布了您的类型,它 不同,但我确实认为该解决方案也适用于您。np.您得到的堆栈解决方案也应该有效,但您忘记对其进行整形),因此您有一个一维对象数组,当您要求其形状时 - 您得到 (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)

输出 (2,2)

但你要求这样做没有列表。另一种方法是像这样使用“连接”:

a = np.concatenate(a).reshape(len(a),*np.shape(a[0]))

这也会产生你想要的结果。 我们在这里所做的是将元组一个接一个地连接在一起——作为一个大数组,然后将其整形为所需的长度。

编辑:您提供的堆栈解决方案也是如此,之后您忘记了重塑

a= np.stack(a).reshape(len(a),*np.shape(a[0]))