【问题标题】:Why do I have to use np.string_? Why can't I use np.string without the underscore?为什么我必须使用 np.string_?为什么我不能使用没有下划线的 np.string?
【发布时间】:2021-10-23 15:12:55
【问题描述】:

我刚开始学习 NumPy,所以我对它的来龙去脉还是有些茫然。我正在学习如何创建具有特定数据类型的数组。我对此有点困惑:

当我创建一个 int32 数据类型的数组时,它只显示:

a = np.zeros((2, 3), dtype=np.int32)
print(a)
print(a.dtype)

打印语句显示:int32

当我创建一个浮点数据类型的数组时,它只显示:

a = np.array([1, 2, 3, 4], dtype=np.float)
print(a)
print(a.dtype)

打印语句显示:float64

但是,当我创建一个数据类型字符串的数组时,它没有类似的输出:

a = np.array([1,2,3,4,5,6], dtype=np.string_)

print(a)
print(a.dtype)

打印语句显示:

[b'1' b'2' b'3' b'4' b'5' b'6']
|S1

为什么?这是什么意思?还有,为什么我不能选择dtype=np.string?为什么我需要下划线dtype=np.string_?

【问题讨论】:

  • 另见stackoverflow.com/a/6205237/982257我认为下划线的原因是双重的:有些人会倾向于(反对推荐)from numpy import *,这些下划线名称至少会阻止它们覆盖基本的Python内置插件(虽然不是全部......)。否则,在代码编辑器和其他东西中,它还会阻止它们在某些情况下像所说的内置插件一样被语法突出显示......
  • @Iguananaut 它没有回答。我想知道为什么我使用 np.string 会出错。看起来我需要下划线 np.string_
  • 只是因为np.string 没有定义。 _ 在语法上没有什么特别之处,它只是一个命名决定,其他 dtype 始终遵循。 github.com/numpy/numpy/pull/6103 对于相同的结果,您也可以使用 np.array(..., dtype=bytes) 或者如果您想要正常的 unicode 字符串,np.array(..., dtype=str)。您不必使用 Numpy 别名。
  • @Iguananaut 明白了!谢谢各位!很有帮助!

标签: python numpy


【解决方案1】:

如您所见,如果您只是这样做:

>>> np.string_
<class 'numpy.bytes_'>
>>> 

它会自动为每个值提供一个numpy.bytes_ 对象。'

所以你应该这样做np.str_如下:

>>> np.array([1,2,3,4,5,6], dtype=np.str_)
array(['1', '2', '3', '4', '5', '6'], dtype='<U1')
>>> 

它给出了一个常规的 numpy 标量字符串 dtype,它与常规的 str 相同。

只使用str 会更容易:

>>> np.array([1,2,3,4,5,6], dtype=str)
array(['1', '2', '3', '4', '5', '6'], dtype='<U1')
>>> 

【讨论】:

  • 感谢您的回答。所以看起来我可以使用 str、str_ 和 string_,但不能使用字符串。如果我这样做,我会得到一个错误。回溯(最后一次调用):文件“c:/Users/Desktop/1.py”,第 134 行,在 g = np.array([1,2,3,4], dtype=np.string ) 文件“C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\numpy_init_.py”,第 214 行,在getattr raise AttributeError("module {!r} has no attribute " AttributeError: module 'numpy' has no attribute 'string'
  • @SpamMeUpScottie Numpy 不幸的是没有string 的属性...,
  • 完全同意,但无法投票。我需要至少 15 个代表。
  • AttributeError 告诉你原因。从模式进行投影不如阅读文档可靠。
【解决方案2】:

什么意思?

简单来说S1是长度为1的字符串,考虑下面的例子

import numpy as np
arr1 = np.array(['A','A','A'],dtype=np.string_)
arr3 = np.array(['ABC','ABC','ABC'],dtype=np.string_)
arr5 = np.array(['ABCDE','ABCDE','ABCDE'],dtype=np.string_)
print(arr1.dtype)  # |S1
print(arr3.dtype)  # |S3
print(arr5.dtype)  # |S5

注意与另一个 numpy 数据类型的类比 - 如果您知道您有一定数量的说长度为 5 的字符串,您可以轻松计算所需的内存,例如 uint8 或 int32,而不是可变长度字符串。

【讨论】:

  • 谢谢!这完全有道理。现在,如果可以的话,有两个问题。数组输出的每个元素旁边都有一个 b。为什么?此外,如果我改用 np.str ,它会打印
猜你喜欢
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多