如何在numpy中将字符串赋值给数组?

13

当我尝试像这样将一个字符串分配给数组:

CoverageACol[0,0] = "Hello" 

我得到了以下错误

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    CoverageACol[0,0] = "hello"
ValueError: setting an array element with a sequence.

然而,给一个整数赋值不会导致错误:

CoverageACol[0,0] = 42

CoverageACol是一个NumPy数组。

请帮忙!谢谢!

2个回答

23
你之所以会得到这个错误是因为NumPy的数组是同一类型的多维表格。这与普通Python中的多维列表-列表不同,你可以在列表中拥有不同类型的对象。 普通Python:
>>> CoverageACol = [[0, 1, 2, 3, 4],
                    [5, 6, 7, 8, 9]]
 
>>> CoverageACol[0][0] = "hello"

>>> CoverageACol
    [['hello', 1, 2, 3, 4], 
     [5, 6, 7, 8, 9]]

NumPy:

>>> from numpy import *

>>> CoverageACol = arange(10).reshape(2,5)

>>> CoverageACol
    array([[0, 1, 2, 3, 4],
           [5, 6, 7, 8, 9]])

>>> CoverageACol[0,0] = "Hello" 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/biogeek/<ipython console> in <module>()

ValueError: setting an array element with a sequence.

所以,这取决于您想要实现什么目标,为什么要在一个由数字填充的数组中存储字符串?如果这确实是您想要的,您可以将NumPy数组的数据类型设置为字符串:

>>> CoverageACol = array(range(10), dtype=str).reshape(2,5)

>>> CoverageACol
    array([['0', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S1')

>>> CoverageACol[0,0] = "Hello"

>>> CoverageACol
    array([['H', '1', '2', '3', '4'],
         ['5', '6', '7', '8', '9']], 
         dtype='|S1')

注意只有Hello的第一个字母被分配了。如果你想要整个单词被分配,你需要设置一个数组协议类型的字符串

>>> CoverageACol = array(range(10), dtype='a5').reshape(2,5)

>>> CoverageACol: 
    array([['0', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S5')

>>> CoverageACol[0,0] = "Hello"

>>> CoverageACol
    array([['Hello', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S5')

4
使用 dtype=object 也可以达到相同的效果:https://dev59.com/pWUq5IYBdhLWcg3wQ-Xk - Anton Tarasenko
在你的代码行中overageACol = array(range(10), dtype=str).reshape(2,5),是否可以将 dtype 改为 list 或者 dict - Ender Look

7
您需要设置数组数据类型
CoverageACol = numpy.array([["a","b"],["c","d"]],dtype=numpy.dtype('a16'))

这使得ConerageACol成为一个长度为16的字符串数组(a)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接