将数据字符串写入NumPy字符数组?

use*_*060 5 python numpy

我想将数据字符串写入NumPy数组.伪代码:

d = numpy.zeros(10, dtype = numpy.character)
d[1:6] = 'hello'
Run Code Online (Sandbox Code Playgroud)

示例结果:

d=
  array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
        dtype='|S1')
Run Code Online (Sandbox Code Playgroud)

如何使用NumPy最自然有效地完成这项工作?

我不想要for循环,生成器或任何迭代.与伪代码一样,可以使用一个命令吗?

Pau*_*aul 3

只需显式地将文本设为 a list(而不是可从 Python 迭代),NumPy就会自动理解它:

>>> text = 'hello'
>>> offset = 1
>>> d[offset:offset+len(text)] = list(text)
>>> d

array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
      dtype='|S1')
Run Code Online (Sandbox Code Playgroud)

  • 我尝试使用 iter 来避免巨大字符串的内存开销。你不会相信 numpy 做了什么 --- d[1:6]=iter('hello') (2认同)