由于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数组的数据类型设置为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分配了第一个字母。如果要分配整个单词,则需要设置一个数组协议类型的字符串:
>>> 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')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)