【问题标题】:Numpy: Check array for string data typeNumpy:检查数组的字符串数据类型
【发布时间】:2012-06-03 03:43:19
【问题描述】:

如何确定 Numpy 数组是否包含字符串?数组a in

a = np.array('hi world')

具有数据类型dtype('|S8'),其中8 指的是字符串中的字符数。

我看不出正则表达式(例如re.match('\|S\d+', a.dtype))在这里如何工作,因为数据类型不仅仅是'|S8'

【问题讨论】:

    标签: python arrays string


    【解决方案1】:
    a.dtype.char == 'S'
    

    a.dtype.type is np.string_
    

    NumPy docs, Data type objects, Attributes

    【讨论】:

    • 我注意到还有 a.dtype.kind == 'S'。甜!
    • 请注意:似乎这需要在 Python 3.x 中为 a.dtype.type is np.str_
    • 对于 Python 2.x 3.x,您可以针对 a.dtype.kind in {'U', 'S'} 进行测试以捕获字符串和 unicode。
    • 如果将字符串放入带有字符“O”的对象数组中会发生什么?
    • a.dtype.type is np.string_ or a.dtype.type is np.str_ 是另一种选择
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2015-02-08
    • 2017-09-24
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多