你之所以会得到这个错误是因为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')
dtype=object
也可以达到相同的效果:https://dev59.com/pWUq5IYBdhLWcg3wQ-Xk - Anton TarasenkooverageACol = array(range(10), dtype=str).reshape(2,5)
,是否可以将dtype
改为list
或者dict
? - Ender Look