python - 将 python 列表转换为 numpy 结构化数组时维护字符串

标签 python numpy

我有一个如下所示的数据结构:

data = [ ('a', 1.0, 2.0),
         ('b', 2.0, 4.0),
         ('c', 3.0, 6.0) ]

我想使用 numpy 将其转换为结构化数组。但是,当我尝试以下操作时,我保留了 float 但丢失了字符串信息:

import numpy
x = numpy.array(data, dtype=[('label', str), ('x', float), ('y', float)])
print x

导致:

>>> [('', 1.0, 2.0) ('', 2.0, 4.0) ('', 3.0, 6.0)]

谁能解释为什么会这样,以及我如何保留字符串信息?

最佳答案

把数组打印出来再仔细看就可以看出问题了:

>>> numpy.array(data, dtype=[('label', str), ('x', float), ('y', float)])
array([('', 1.0, 2.0), ('', 2.0, 4.0), ('', 3.0, 6.0)], 
      dtype=[('label', '|S0'), ('x', '<f8'), ('y', '<f8')])

第一个字段的数据类型为 '|S0' -- 零宽度 字符串字段。使字符串字段更长——这里是一个 2 字符的字符串字段:

>>> numpy.array(data, dtype=[('label', 'S2'), ('x', float), ('y', float)])
array([('a', 1.0, 2.0), ('b', 2.0, 4.0), ('c', 3.0, 6.0)], 
      dtype=[('label', '|S2'), ('x', '<f8'), ('y', '<f8')])

您也可以按照这种方式进行操作,如文档所述here :

>>> numpy.array(data, dtype=[('label', (str, 2)), ('x', float), ('y', float)])
array([('a', 1.0, 2.0), ('b', 2.0, 4.0), ('c', 3.0, 6.0)], 
      dtype=[('label', '|S2'), ('x', '<f8'), ('y', '<f8')])

关于python - 将 python 列表转换为 numpy 结构化数组时维护字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12873975/

相关文章:

python - 在 python 中向量化嵌套 for 循环以实现依赖于索引的函数

用于 MD5 哈希的 Python 正则表达式

python - 如何调用需要 "quotes"字符串的函数?

python - 如何避免 Matplotlib 圆环图上重叠的楔形下降标签?

python - 从两个 numpy 数组中删除重复元素

python - 找到多项式曲线之间交点的有效方法?

Python Kivy 不会使用 SDL2,坚持使用 pygame

python - 中序遍历的生成器函数

python - 箱线图屏蔽数组

python - 按数组numpy过滤