将numpy字符串字段数组转换为数字格式

Mad*_*ist 5 python numpy

我有一个字符串数组,分为三个字段:

x = np.array([(-1, 0, 1),
              (-1, 1, 0),
              (0, 1, -1),
              (0, -1, 1)],
             dtype=[('a', 'S2'),
                    ('b', 'S2'),
                    ('c', 'S2')])
Run Code Online (Sandbox Code Playgroud)

我想转换为数字数组(类型np.int8为首选项,但不是必需的),形状为4x3,而不是字段.

我的一般方法是转换为'S2'类型的4x3数组,然后用astype它来使它成为数字.唯一的问题是,唯一的办法我能想到既包括中viewnp.lib.stride_tricks.as_strided,这似乎不是一个非常强大的解决方案:

y = np.lib.stride_tricks.as_strided(x.view(dtype='S2'),
                                    shape=(4, 3), strides=(6, 2))
z = y.astype(np.int8)
Run Code Online (Sandbox Code Playgroud)

这适用于此处显示的玩具箱,但我觉得必须有一种更简单的方法来解压缩具有所有具有相同dtype的字段的数组.什么是更强大的替代方案?

M1L*_*L0U 1

最新版本的 numpy 1.16 添加了structured_to_unstructured解决此目的的功能:

from numpy.lib.recfunctions import structured_to_unstructured
y = structured_to_unstructured(x)  # 2d array of 'S2'
z = y.astype(np.int8)
Run Code Online (Sandbox Code Playgroud)

在以前版本的 numpy 中,您可以组合x.datanp.frombuffer从内存中的相同数据创建另一个数组,而无需使用步幅。但它不会带来性能增益,因为计算是由 fromS2到 的转换驱动的int8

from numpy.lib.recfunctions import structured_to_unstructured
y = structured_to_unstructured(x)  # 2d array of 'S2'
z = y.astype(np.int8)
Run Code Online (Sandbox Code Playgroud)