【问题标题】:Understanding NumPy dtype "c" with strings用字符串理解 NumPy dtype "c"
【发布时间】:2019-03-28 18:23:18
【问题描述】:

目标:str 转换为np.ndarray of bytes,大小为1:

import numpy as np
np.array("abc", dtype=[whatever])

没有 dtype 的实际结果:array('abc', dtype='<U3')

期望的结果:array([b'a', b'b', b'c'], dtype=[whatever] 这让我可以使用切片来获取

我找到但不明白的解决方法:

np.array("abc", dtype='c')
# array([b'a', b'b', b'c'], dtype='|S1')

我通过反复试验找到了这个,认为'c' 可能意味着“字符”

我不明白的地方: 为什么dtype='c' 会这样工作?根据arrays.dtypes reference'c' 是“复浮点”的缩写,而'|S1' 是长度为 1 的“零终止字节(不推荐)”。

同样直接使用 '|S1' 作为dtype 会忽略除第一个字符之外的每个字符,这不是我所期望的,但我想它只是将"abc" 作为一个参数,而b'a' 就是结果如果只指定一个字节为dtype:

np.array("abc", dtype='|S1')
# array(b'a', dtype='|S1')

问题:

  1. 为什么dtype='c' 会这样工作?
  2. (如果 dtype='c' 只是“偶然”工作,那么“正确的方法”是什么?)

PS: 是的,有一个np.chararray,但根据链接文档:

chararray 类的存在是为了向后兼容 Numarray,不建议用于新开发。从 numpy 1.4 开始,如果需要字符串数组,建议使用 dtype object_、string_ 或 unicode_ 的数组,并使用 numpy.char 模块中的 free 函数进行快速向量化字符串操作。

但是推荐的 dtypes object_string_unicode_ 不要将字符串拆分为字符,而是返回带有一个元素的 ndarray

【问题讨论】:

  • 'c' 列在'Array-protocol type strings (see The Array Interface)' 部分下,其中字母必须后跟尺寸编号,如np.dtype('c16')。它不适用于 Python 代码中的独立 'c' 字符串。 np.typecodes['Character'] 返回“c”。
  • 还比较np.dtype('c')np.dtype('c8')npdtype('c4')(错误)、np.dtype('S3')
  • @hpaulj 我知道我使用'c' 的结果不是复数,而是字节字符。但即使np.typecodes['Character'] 返回'c'np.array("abc", dtype=np.character) 也不会返回与np.array("abc", dtype='c') 相同的结果。

标签: python arrays numpy char


【解决方案1】:

对我来说这似乎是一个错误。请注意,如果您不指定字符代码“c”之后的字节数,则 dtype 实际上是“S1”,而不是复数浮点数。查看 dtypes 的这些属性:

>>> dt_S1 = np.dtype('S1')
>>> dt_S1, dt_S1.kind, dt_S1.name, dt_S1.char
(dtype('S1'), 'S', 'bytes8', 'S')

>>> dt_c = np.dtype('c')
>>> dt_c, dt_c.kind, dt_c.name, dt_c.char))
(dtype('S1'), 'S', 'bytes8', 'c')

>>> dt_c8 = np.dtype('c8')
>>> dt_c8, dt_c8.kind, dt_c8.name, dt_c8.char
(dtype('complex64'), 'c', 'complex64', 'F')

所以人们会期望np.array('abc', dtype='c')np.array('abc', dtype='S1') 返回相同的结果array(b'a', dtype='S1'),或者前者会像np.array('abc', dtype='c8') 一样给出错误。

恕我直言,完成任务的正确方法是:

np.array(list('abc'), dtype='S1')

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2014-03-24
    • 2014-01-05
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 2017-03-21
    • 2021-12-13
    相关资源
    最近更新 更多