python - numpy 中 str 类输入的默认 dtype 是什么?

标签 python string numpy numpy-dtype

我只是想在创建 ndarray 时确认字符串的默认数据类型是否为 unicode。我找不到任何清楚说明这一点的引用资料。可能是太明显了,不需要说明。

指定数据类型时:

>>> import numpy as np
>>> g = np.array([['a', 'b'],['c', 'd']], dtype='S')
>>> g
array([[b'a', b'b'],
       [b'c', b'd']], 
      dtype='|S1')

不指定数据类型:

>>> g = np.array([['a', 'b'],['c', 'd']])
>>> g
array([['a', 'b'],
       ['c', 'd']], 
      dtype='<U1')

此外,当指定 dtype 时,文字 b 表示什么。根据文档,它指示 bool,但此处似乎并非如此。

有人可以澄清一下吗?

最佳答案

b'...' 表示它是字节字符串,字符串数组的默认 dtype 取决于字符串的种类。 Unicode(python 3 字符串是 unicode)是 U 和 Python 2 str 或 Python 3 bytes 有数据类型 S .您可以在 NumPy documentation here 中找到数据类型的解释。

Array-protocol type strings

The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are:

  • '?' boolean
  • 'b' (signed) byte
  • 'B' unsigned byte
  • 'i' (signed) integer
  • 'u' unsigned integer
  • 'f' floating-point
  • 'c' complex-floating point
  • 'm' timedelta
  • 'M' datetime
  • 'O' (Python) objects
  • 'S', 'a' zero-terminated bytes (not recommended)
  • 'U' Unicode string
  • 'V' raw data (void)

但是,在您的第一种情况下,您实际上强制 NumPy 将其转换为字节,因为您指定了dtype='S'

关于python - numpy 中 str 类输入的默认 dtype 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051977/

相关文章:

python - 我可以在没有任何转储的情况下 pickle 字符串吗?

python - 如何拦截对特定页面的所有请求(以Python为例)

string - 沿正则表达式拆分字符串,但保持匹配

python - 构建 Blaze 需要什么 Clang++?

python - 从 FOR 循环创建 numpy 数组的最佳方法

python - Mathematica 中的临时变量

python - 我可以安全地删除 Django 的空 __init__ 文件吗?

vb.net - 在 VB.NET 中拆分字符串

c++ - 调用临时对象的方法安全吗?

python - 使用 bool 向量选择 Numpy 二维数组中的行