当我尝试将字符串分配给这样的数组时:
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数组。
请帮忙!谢谢!
答案 0 :(得分:15)
您收到错误,因为NumPy的数组是homogeneous, meaning it is a multidimensional table of elements all of the same type。这与“常规”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数组的数据类型设置为string:
>>> 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
的第一个字母。如果您希望分配整个单词,则需要设置an array-protocol type string:
>>> 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')
答案 1 :(得分:6)