将一个二维的numpy数组转换为结构化数组。

44

我想将一个二维数组转换为带有命名字段的结构化数组。我希望二维数组中的每一行都成为结构化数组中的一条新记录。不幸的是,我尝试过的所有方法都没有按照我的预期工作。

我从以下内容开始:

>>> myarray = numpy.array([("Hello",2.5,3),("World",3.6,2)])
>>> print myarray
[['Hello' '2.5' '3']
 ['World' '3.6' '2']]

我想要将它转换成类似于这样的形式:

>>> newarray = numpy.array([("Hello",2.5,3),("World",3.6,2)], dtype=[("Col1","S8"),("Col2","f8"),("Col3","i8")])
>>> print newarray
[('Hello', 2.5, 3L) ('World', 3.6000000000000001, 2L)]

我的尝试:

>>> newarray = myarray.astype([("Col1","S8"),("Col2","f8"),("Col3","i8")])
>>> print newarray
[[('Hello', 0.0, 0L) ('2.5', 0.0, 0L) ('3', 0.0, 0L)]
 [('World', 0.0, 0L) ('3.6', 0.0, 0L) ('2', 0.0, 0L)]]

>>> newarray = numpy.array(myarray, dtype=[("Col1","S8"),("Col2","f8"),("Col3","i8")])
>>> print newarray
[[('Hello', 0.0, 0L) ('2.5', 0.0, 0L) ('3', 0.0, 0L)]
 [('World', 0.0, 0L) ('3.6', 0.0, 0L) ('2', 0.0, 0L)]]

这两种方法都尝试将myarray中的每个元素转换为指定dtype的记录,因此会插入多余的零。我无法弄清如何将每行转换为记录。

另一种尝试:

>>> newarray = myarray.copy()
>>> newarray.dtype = [("Col1","S8"),("Col2","f8"),("Col3","i8")]
>>> print newarray
[[('Hello', 1.7219343871178711e-317, 51L)]
 [('World', 1.7543139673493688e-317, 50L)]]

这次不进行实际的转换,而只是将内存中的现有数据重新解释为新的数据类型。

我开始使用的数组是从文本文件中读取的。数据类型事先未知,因此无法在创建时设置dtype。我需要一种高性能且优雅的解决方案,适用于各种一般情况,因为我将针对大量不同的应用程序进行这种类型的转换。

谢谢!

5个回答

42
你可以使用 numpy.core.records.fromarrays 从一个(平坦的)数组列表中"创建记录数组",示例如下:
>>> import numpy as np
>>> myarray = np.array([("Hello",2.5,3),("World",3.6,2)])
>>> print myarray
[['Hello' '2.5' '3']
 ['World' '3.6' '2']]


>>> newrecarray = np.core.records.fromarrays(myarray.transpose(), 
                                             names='col1, col2, col3',
                                             formats = 'S8, f8, i8')

>>> print newrecarray
[('Hello', 2.5, 3) ('World', 3.5999999046325684, 2)]

我尝试做类似的事情。 我发现当numpy从现有的2D数组创建结构化数组(使用np.core.records.fromarrays)时,它将2-D数组中的每一列(而不是每一行)视为一个记录。 因此您必须对其进行转置。 Numpy的这种行为似乎不太直观,但也许有很好的原因。


8
使用 fromrecords 可以避免使用 transpose() - Ruggero Turra
5
这将创建一个记录数组,而不是结构化的ndarray。 - mueslo

12

如果数据最初是元组列表,则创建结构化数组就很简单:

In [228]: alist = [("Hello",2.5,3),("World",3.6,2)]
In [229]: dt = [("Col1","S8"),("Col2","f8"),("Col3","i8")]
In [230]: np.array(alist, dtype=dt)
Out[230]: 
array([(b'Hello',  2.5, 3), (b'World',  3.6, 2)], 
      dtype=[('Col1', 'S8'), ('Col2', '<f8'), ('Col3', '<i8')])

问题在于元组列表已被转换为二维字符串数组:

In [231]: arr = np.array(alist)
In [232]: arr
Out[232]: 
array([['Hello', '2.5', '3'],
       ['World', '3.6', '2']], 
      dtype='<U5')
我们可以使用众所周知的zip*方法来“转置”这个数组 - 实际上我们需要进行双重转置:
In [234]: list(zip(*arr.T))
Out[234]: [('Hello', '2.5', '3'), ('World', '3.6', '2')]

zip 已经为我们提供了一个元组列表。现在,我们可以使用所需的 dtype 重新创建数组:

In [235]: np.array(_, dtype=dt)
Out[235]: 
array([(b'Hello',  2.5, 3), (b'World',  3.6, 2)], 
      dtype=[('Col1', 'S8'), ('Col2', '<f8'), ('Col3', '<i8')])

被接受的答案使用了fromarrays

In [236]: np.rec.fromarrays(arr.T, dtype=dt)
Out[236]: 
rec.array([(b'Hello',  2.5, 3), (b'World',  3.6, 2)], 
          dtype=[('Col1', 'S8'), ('Col2', '<f8'), ('Col3', '<i8')])

在内部,fromarrays 采用了常见的 recfunctions 方法:创建目标数组,并按字段名称复制值。 实际上它执行的操作是:

Internally, fromarrays 采用了常见的 recfunctions 方法:创建目标数组,并按字段名称复制值。实际上它执行的操作是:

In [237]: newarr = np.empty(arr.shape[0], dtype=dt)
In [238]: for n, v in zip(newarr.dtype.names, arr.T):
     ...:     newarr[n] = v
     ...:     
In [239]: newarr
Out[239]: 
array([(b'Hello',  2.5, 3), (b'World',  3.6, 2)], 
      dtype=[('Col1', 'S8'), ('Col2', '<f8'), ('Col3', '<i8')])

10

我想

new_array = np.core.records.fromrecords([("Hello",2.5,3),("World",3.6,2)],
                                        names='Col1,Col2,Col3',
                                        formats='S8,f8,i8')

这就是你想要的。


2
这将返回一个记录数组(np.recarray),而不是一个带有dtype的结构化数组(np.ndarray)。 - Gaël Écorchard

3

好的,我已经挣扎了一段时间,但我找到了一种方法来实现这一点,这不需要太多的努力。如果这段代码很“脏”,我会道歉的...

让我们从一个二维数组开始:

mydata = numpy.array([['text1', 1, 'longertext1', 0.1111],
                     ['text2', 2, 'longertext2', 0.2222],
                     ['text3', 3, 'longertext3', 0.3333],
                     ['text4', 4, 'longertext4', 0.4444],
                     ['text5', 5, 'longertext5', 0.5555]])

所以我们最终得到一个4列5行的二维数组:
mydata.shape
Out[30]: (5L, 4L)

要使用numpy.core.records.arrays,我们需要将输入参数作为数组列表提供,所以:
tuple(mydata)
Out[31]: 
(array(['text1', '1', 'longertext1', '0.1111'], 
      dtype='|S11'),
 array(['text2', '2', 'longertext2', '0.2222'], 
      dtype='|S11'),
 array(['text3', '3', 'longertext3', '0.3333'], 
      dtype='|S11'),
 array(['text4', '4', 'longertext4', '0.4444'], 
      dtype='|S11'),
 array(['text5', '5', 'longertext5', '0.5555'], 
      dtype='|S11'))

这将为每行数据生成一个单独的数组,但我们需要按列输入数组,因此我们需要:

tuple(mydata.transpose())
Out[32]: 
(array(['text1', 'text2', 'text3', 'text4', 'text5'], 
      dtype='|S11'),
 array(['1', '2', '3', '4', '5'], 
      dtype='|S11'),
 array(['longertext1', 'longertext2', 'longertext3', 'longertext4',
       'longertext5'], 
      dtype='|S11'),
 array(['0.1111', '0.2222', '0.3333', '0.4444', '0.5555'], 
      dtype='|S11'))

最后,它需要是一个数组的列表,而不是元组,所以我们将上述内容用list()进行包装,如下所示:
list(tuple(mydata.transpose()))

这是我们的数据输入参数已排序... 接下来是数据类型:
mydtype = numpy.dtype([('My short text Column', 'S5'),
                       ('My integer Column', numpy.int16),
                       ('My long text Column', 'S11'),
                       ('My float Column', numpy.float32)])
mydtype
Out[37]: dtype([('My short text Column', '|S5'), ('My integer Column', '<i2'), ('My long text Column', '|S11'), ('My float Column', '<f4')])

好的,现在我们可以将其传递给numpy.core.records.array():

myRecord = numpy.core.records.array(list(tuple(mydata.transpose())), dtype=mydtype)

...并祈祷好运:

myRecord
Out[36]: 
rec.array([('text1', 1, 'longertext1', 0.11110000312328339),
       ('text2', 2, 'longertext2', 0.22220000624656677),
       ('text3', 3, 'longertext3', 0.33329999446868896),
       ('text4', 4, 'longertext4', 0.44440001249313354),
       ('text5', 5, 'longertext5', 0.5554999709129333)], 
      dtype=[('My short text Column', '|S5'), ('My integer Column', '<i2'), ('My long text Column', '|S11'), ('My float Column', '<f4')])

好的!您可以按列名进行索引,比如:

myRecord['My float Column']
Out[39]: array([ 0.1111    ,  0.22220001,  0.33329999,  0.44440001,  0.55549997], dtype=float32)

我希望这能帮到你,因为在最终找到这种方法之前,我浪费了很多时间尝试使用numpy.asarray和mydata.astype等方法来使它起作用。


3
在这里,“记录数组”和“结构化数组”之间存在很多混淆。以下是我对结构化数组的简短解决方案。
dtype = np.dtype([("Col1","S8"),("Col2","f8"),("Col3","i8")])
myarray = np.array([("Hello",2.5,3),("World",3.6,2)], dtype=dtype)
np.array(np.rec.fromarrays(myarray.transpose(), names=dtype.names).astype(dtype=dtype).tolist(), dtype=dtype)

因此,在假设dtype已定义的情况下,这是一行代码。

还有一种备选方案在 https://numpy.org/doc/stable/user/basics.rec.html 中有记录:“recarray = myarray.view(dtype=((np.record, myarray.dtype)), type=np.recarray); recarray.view(recarray.dtype.fields or recarray.dtype, np.ndarray)”。 - Gaël Écorchard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接