【问题标题】:converting numpy array of string fields to numerical format将字符串字段的numpy数组转换为数字格式
【发布时间】:2019-01-29 09:22:56
【问题描述】:

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

x = np.array([(-1, 0, 1),
              (-1, 1, 0),
              (0, 1, -1),
              (0, -1, 1)],
             dtype=[('a', 'S2'),
                    ('b', 'S2'),
                    ('c', 'S2')])

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

我的一般方法是转换为 '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)

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

【问题讨论】:

  • 使用列表是将结构化数组转换为简单数据类型的最可靠方法:np.array(x.tolist(),'int8')
  • @hpaulij。我可能会选择那个答案,尽管我现在需要第三份数据副本让我很困扰。
  • 为什么是 S2?你是怎么看这篇文章的?
  • @Andy。 stackoverflow.com/q/53953116/2988730。我问这个问题是为了无耻地抄袭 hpaulj 提供的答案。
  • @hpaulj。我使用了您建议的技术:stackoverflow.com/a/53954336/2988730

标签: python numpy


【解决方案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)

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

n = 1000

def f1(x):
    y = np.lib.stride_tricks.as_strided(x.view(dtype='S2'),
                                        shape=(n, 3),
                                        strides=(6, 2))
    return y.astype(np.int8)

def f2(x):
    y = np.frombuffer(x.data, dtype='S2').reshape((n, 3))
    return y.astype(np.int8)


x = np.array([(i%3-1, (i+1)%3-1, (i+2)%3-1)
              for i in xrange(n)],
             dtype='S2,S2,S2')

z1 = f1(x)
z2 = f2(x)
assert (z1==z2).all()

【讨论】:

  • 我并不担心性能。正如你所说,转换将不可避免地占主导地位。它只是在操作我不确定的字段数组。
  • 对我来说跨步技巧有点像正则表达式。我有时会发现自己有两个问题。
  • 在 numpy 中添加了 structured_to_unstructured>=1.16,这正是您想要的!
  • 谢谢。当你问的时候,你学到的东西是惊人的。不幸的是,我已经投票了:)
猜你喜欢
  • 2016-03-10
  • 1970-01-01
  • 2013-05-05
  • 2019-12-15
  • 1970-01-01
  • 2021-04-26
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多