我只是想在创建 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/