【问题标题】:Python ndarray with elements of different types具有不同类型元素的 Python ndarray
【发布时间】:2018-12-11 11:40:34
【问题描述】:

我想创建一个数组来保存混合类型 - 字符串和整数。

以下代码未按预期工作 - 所有元素都输入为字符串。

>>> a=numpy.array(["Str",1,2,3,4])
>>> print a
['Str' '1' '2' '3' '4']
>>> print type(a[0]),type(a[1])
<type 'numpy.string_'> <type 'numpy.string_'>

数组的所有元素都输入为“numpy.string_”

但是,奇怪的是,如果我将其中一个元素作为“无”传递,则类型会按预期显示:

>>> a=numpy.array(["Str",None,2,3,4])
>>> print a
['Str' None 2 3 4]
>>> print type(a[0]),type(a[1]),type(a[2])
<type 'str'> <type 'NoneType'> <type 'int'>

因此,包含“无”元素为我提供了一种解决方法,但我想知道为什么会这样。 即使我没有将其中一个元素作为 None 传递,难道不应该在传递元素时输入它们吗?

【问题讨论】:

  • 两者都不是真正重复的,第二个更好,但是关于None的更明确的解释对于OP来说会更好
  • 建议的副本只解释了字符串 dtype:stackoverflow.com/questions/49751000/…

标签: python arrays numpy types mixed


【解决方案1】:

添加None 的另一种方法是明确dtype:

In [80]: np.array(["str",1,2,3,4])
Out[80]: array(['str', '1', '2', '3', '4'], dtype='<U3')
In [81]: np.array(["str",1,2,3,4], dtype=object)
Out[81]: array(['str', 1, 2, 3, 4], dtype=object)

创建一个对象 dtype 数组并从列表中填充它是另一种选择:

In [85]: res = np.empty(5, object)
In [86]: res
Out[86]: array([None, None, None, None, None], dtype=object)
In [87]: res[:] = ['str', 1, 2, 3, 4]
In [88]: res
Out[88]: array(['str', 1, 2, 3, 4], dtype=object)

这里不需要,但是当你想要一个列表数组时它很重要。

【讨论】:

    【解决方案2】:

    强烈建议不要使用 NumPy 中的混合类型。你失去了向量化计算的好处。在这种情况下:

    • 对于您的第一个数组,NumPy 决定将您的 数组到 3 个或更少字符的字符串的统一数组。
    • 对于您的第二个数组,None 不允许作为 NumPy 中的“字符串”变量, 所以 NumPy 使用标准的object dtype。 object dtype 表示指向任意类型的指针的集合。

    您可以在打印数组的 dtype 属性时看到这一点:

    print(np.array(["Str",1,2,3,4]).dtype)     # <U3
    print(np.array(["Str",None,2,3,4]).dtype)  # object
    

    这应该是完全可以预料的。 NumPy 对同质类型有强烈的偏好,事实上你应该对任何有意义的计算有这种偏好。否则,Python list 可能是更合适的数据结构。

    有关 NumPy 如何优先考虑 dtype 选择的更详细说明,请参阅:

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      相关资源
      最近更新 更多