将3d numpy数组转换为2d numpy数组(其中内容为元组)

New*_*ler 6 python numpy

我有以下3d numpy数组np.random.rand(6602, 3176, 2)。我想将其转换为2d数组(numpypandas.DataFrame),其中内部的每个值都是一个元组,使得形状为(6602, 3176)

这个问题帮助我了解了如何减小尺寸,但是我仍然对元组位感到困惑。

Pau*_*zer 7

这是一个单行代码,在完整的 (6602, 3176, 2) 问题上需要几秒钟的时间

a = np.random.rand(6602, 3176, 2)

b = a.view([(f'f{i}',a.dtype) for i in range(a.shape[-1])])[...,0].astype('O')
Run Code Online (Sandbox Code Playgroud)

这里的技巧是将 viewcast 转换为正好跨越一行的复合 dtype。当这样一个复合数据类型被转换为对象时,每个复合元素都被转换为一个元组。

更新(帽子提示@hpaulj)有一个库函数可以精确地执行我们手动执行的视图转换:numpy.lib.recfunctions.unstructured_to_structured

使用它,我们可以编写上述内容的可读性更强的版本:

import numpy.lib.recfunctions as nlr

b = nlr.unstructured_to_structured(a).astype('O')
Run Code Online (Sandbox Code Playgroud)

  • `numpy.lib.recfunctions.unstructured_to_structured` 是用于将数组转换为结构化数据类型的新推荐工具。在这种情况下,它只是消除了“[...,0]”步骤的需要。`unstructed_to_structed(a)` 就足够了。 (3认同)