【问题标题】:Python convert Python string to Numpy unicode stringPython 将 Python 字符串转换为 Numpy unicode 字符串
【发布时间】:2018-03-06 09:50:12
【问题描述】:

我不知道如何将 Python 字符串转换为 numpy unicode 字符串

import numpy as np

py_str = "hello world"
#numpy_str = ?

【问题讨论】:

  • 什么是 numpy unicode 字符串?您使用的是 Python 2 还是 3?
  • 为什么不np.array(py_str)?在 Py3 中,这将是未编码的。或np.unicode_(py_str)。通常,单个元素数组更有用,尽管它们共享许多相同的属性和方法。

标签: python string numpy


【解决方案1】:

要将 Python 字符串转换为 numpy 字符串,您只需使用 numpy 构造函数即可。

>>> import numpy as np
>>> py_str = "hello world"
>>> numpy_str = np.string_(py_str)
>>> type(numpy_str)
<type 'numpy.string_'>

编辑:

按照@hpaulj 的建议,您可能会发现numpy_strdtype 是string88 而不是unicode。接下来,我添加代码以通过内容、类型和 dtype 检查将其转换为 unicode。

>>> numpy_str
'hello world'
>>> type(numpy_str)
<type 'numpy.string_'>
>>> numpy_str.dtype.name
'string88'

>>> numpy_unicode = numpy_str.astype(unicode)

>>> numpy_unicode
u'hello world'
>>> type(numpy_unicode)
<type 'numpy.unicode_'>
>>> numpy_unicode.dtype.name
'unicode352'

【讨论】:

  • @hpaulj 谢谢。我根据您的建议更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
相关资源
最近更新 更多